Custom Scalars
Recommended background reading#
Custom Scalars in RescriptRelay#
GraphQL allow you to define custom scalars that can be used throughout your schema. In RescriptRelay, you can handle custom scalars in 3 different ways:
- Map custom scalars to an existing type. This is useful if you have something that doesn't need decoding, like a 
Colorscalar that's really just astring. - Map custom scalars to an abstract type. This is useful when you have a custom scalar like a 
Cursorthat you shouldn't touch on the client, but just pass on as-is. - Have RescriptRelay automatically convert your custom scalar values for you at runtime. This is useful when you have a custom scalar like 
Datetimewhich you know you'll always want to convert to aJs.Date.tat runtime, and want to avoid the hassle of doing that manually. 
Defining Custom Scalars#
Custom scalars are defined in the project's relay.config.js (you can read more about relay.config.js here). It's pretty simple, you just add a mapping from scalar name to a custom scalar value. Let's cover all 3 use cases outlined above in an example:
Automatic decoding and encoding of values#
Expanding on the Datetime example above, whenever you want RescriptRelay to automatically convert a custom scalar for you at runtime, do this:
- As in the example above, define the custom scalar mapping as a module. This is decided by that what the mapping points to is a capitalized name, which in Reason means it's a module.
 - Make sure the module you're pointing to exists in your project, and implements this signature:
 
It's of course fine to have more functions and types on your custom scalar module, but it needs to at least have the signature above.
Let's finish this off with some examples.
Examples#
Imagine this query:
If no definition for the custom scalars Datetime or Color were defined in relay.config.js, the generated types would look like this:
But, if we were to add the following definitions for the custom scalars:
The response would instead look like this:
...and currentTime would always be automatically converted using Utils.Datetime.parse, and serialized using Utils.Datetime.serialize if it ever needs to be sent back to the server in a mutation, variables etc. But you don't need to think about that, it all happens automatically.
Great, huh? This means you can model custom scalars any way you want and that makes sense for your use case.