Sitemap

Let’s understand GraphQL scalars

3 min readNov 13, 2018
Photo by VASANTH on Unsplash

In this article, I’ll try to explain what is Scalar types in GraphQL and dive in into how to create your own.

What is Scalar type?— it is the smallest unit inGraphQL, which can’t contain any other types, but just value. GraphQL has predefined Scalar types — String, Digit, Float, Boolean and ID. The benefit of scalars, that they also serve as a validation of your types, so you can add more control over your types. For instance, check if it’s URL, date, email, you name it!

There is a lot of open source Scalar types, which you can use in your project, and I ask you to check them out. But it’s always a case when you need something specific, which is not open sourced yet. GraphQL spec gives us the ability to create our own Scalar types. So let’s check it:

new GraphQLScalarType({
name,
description,
serialize,
parseValue,
parseLiteral
});

While the name and description are self-explanatory. Others need few words and some code to understand:

  • serialize — the function which preparing value to send to the client. Imagine the case where we got boolean from database in the format 0/1, this is the place where you transform your 0’s and 1’s into true and false
  • parseValue and parseLiteral — both of them parsing values, which you’ve received from the client (mutation input). The main difference between them that parseValue is parsing values from variables which are in JSON format (basically the same as you send them), while parseLiteral it’s what you get from the query (inline values) in AST format Here is a nice explanation if you wanna dive deeper.

Let’s check the graphql-js implementation of GraphQLBoolean :

serialize

As you can see, we’re returning value if it’s already boolean and if it’s a finite number we convert it to boolean simply by checking if it’s not a 0. Otherwise throwing an error.

parseValue

This is kinda easy, as variables return to us in JSON format, we can just check if the value is a boolean and return it or throw an error otherwise.

parseLiteral

Here is where it’s getting tricky. Graphql parse query as AST and each value contain few crucial things for us. kind and value. kind is value type from schema but not boolean as you might think, but BooleanValue instead. That’s why we have this helper Kind, which contains all graphql types in more human-readable format, we’re here mostly interested in scalar types, which is type name in uppercase Kind.BOOLEAN Where value as you might guess is just a value.

Conclusion

As you can see, even though it’s a bit tricky, Scalars in GraphQL are quite simple. You can clearly see, that Scalars are making your code more understandable and safer. So I hope you’ve understood why you need them and how to create your own. And don’t forget to share them with the world, by open sourcing them.

--

--

No responses yet