Scalar Coercion

Understand how GraphQL scalar coercion works.

Scalar coercion is a term used by the type system, which translates the values returned by a resolver function into something that upholds the API contract. When we query or mutate data using our GraphQL schema, we need to understand two operations that occur in the GraphQL servers:

  • Result coercion: This is when the contract of a type that we accept from the server is upheld. In other words, it verifies the primitive values or object type.

  • Input coercion: This is the when the contract of a type for input arguments that we’ll pass into the GraphQL query or mutation is upheld.

To fully understand scalar coercion, we have to go into the GraphQL specification. It’s essential to acknowledge that the rules for each scalar type are different. Let’s discuss these rules for each kind, along with the corresponding result and input coercion.

ID

The ID is often used to fetch an object or as a key for a cache. The ID must be a unique identifier. The ID type appears in a JSON response as a String. However, the ID scalar type is not built to be readable by humans. When used as an input type, any string (such as “4”) or integer (such as 4) input value will be accepted as an ID.

If we use a GraphQL client like Apollo, each type should have at least one ID for better caching, while an operation abstraction should be done through Apollo internal redux or relay. ID is often ...