The GraphQL specification includes the following default scalar types:
Boolean. While this covers most of the user cases, often you need to support custom atomic data types (e.g. Date), or you want a version of an existing type that does some validation. To enable this, GraphQL allows you to define custom scalar types.
To define a custom scalar you simply add it to the schema string with the following notation:
Afterwards, you have to define the behavior of your
MyCustomScalar custom scalar by passing an instance of the
GraphQLScalarType class in the resolver map. This instance can be defined in a dependency package or in your own code.
Note that Apollo Client does not currently have a way to automatically interpret custom scalars, so there’s no way to automatically reverse the serialization on the client.
Here, we’ll take the graphql-type-json package as an example to demonstrate what can be done. This npm package defines a JSON GraphQL scalar type.
graphql-type-jsonpackage to your project’s dependencies :1$ npm install --save graphql-type-json
GraphQLJSON is a
If needed, you can define your own GraphQLScalarType instance. This can be done the following way :
Let’s look at a couple of examples to demonstrate how a custom scalar type can be defined.
The goal is to define a
Date data type for returning
Date data type. The
Date data type can be easily serialized as a number using the
getTime() method. Therefore, we would like our GraphQL server to send and receive
Dates as numbers when serializing to JSON. This number will be resolved to a
Date on the server representing the date value. On the client, the user can simply create a new date from the received numeric value.
The following is the implementation of the
Date data type. First, the schema:
Next, the resolver:
In this example, we follow the official GraphQL documentation for the scalar datatype. Let’s say that you have a database field that should only contain odd numbers. First, the schema:
Next, the resolver: