Should I use custom scalars?

I’m learning GraphQL and Apollo for a new project, and found this page about custom scalars Custom scalars - Apollo Server - Apollo GraphQL Docs. I’m using Postgres with Prisma, and have several models with date, date-time, and time fields as well as a few fields storing JSON. Wondering if custom scalars are generally recommended as a best practice? Seems better than just making them all strings.

If so, has anyone else created different custom scalars for a date by itself, vs date-time, vs time only?

I’m using custom scalars for JSON and DATETIME and they work great.

I accessing them via the npm package graphql-scalars. It’s getting 126,770 weekly downloads as of today, so that indicates that they are working well for a lot of people.

In general, yes, custom scalars are definitely something you should use.

Additionally, rather than adding a comment over certain scalars, such as the formatting of a string, you can easily create a custom scalar that has that documentation on it, and then use it so that you don’t have to duplicate your comments everywhere.

If you are going to create a custom scalar for the formatting of a string, for example, I recommend doing simple validation on the scalar’s resolver to make sure that the data given to the client is indeed formatted as you say it should be.

If the format is wrong at runtime, you may want to have a copy of these errors, in which case you can use new ApolloServer({ formatError: error => {...} }) and simply log them out before sending to your client.

I don’t recommend using JSON for scalars, unless you absolutely have to. Using JSON/JSONObject basically removes the point of using GraphQL in the first place. JSON accepts any value that JSON allows, and JSONObject only allows objects. Both of these effectively remove type safety from your schema.