Open In App

GraphQL | Scalars

Scalars are content of the GraphQL Type System. GraphQL scalars are the value types that every field in a GraphQL document ultimately resolves to. It is primitive data types that store single value. There are five built-in scalars in GraphQL but you can define custom made scalars too.

Built-in scalars: Scalar types represent primitive leaf values in a GraphQL type system. GraphQL responses take the form of a hierarchical tree; the leaves on these trees are GraphQL scalars.



Example: Structure of GraphQL Scalar.



The GraphQL scalars have 3 methods. The purpose of these methods is the identification and validation of the data before it is transferred between the client and the server.

Custom Scalars: GraphQL gives developers the power to define custom scalars, appropriate to their own needs. We can declare a custom scalar like below and add it to the schema. To define your own scalar, validations, serializations, and parsers have to be written from scratch. There is also a great package called graphql-scalars ready for use that contains common scalars that might be required.

Example: Now, let’s look at some examples of how these scalars play out. To demo, we will use the below schema.js file to perform this task.

Scalars features:

Reference: https://graphql-ruby.org/type_definitions/scalars.html

Article Tags :