Join us for GraphQL Summit, October 10-12 in San Diego. Use promo code ODYSSEY for $400 off your pass.
Docs
Launch GraphOS Studio
Apollo Server 2 is officially deprecated, with end-of-life scheduled for 22 October 2023. Additionally, certain features are end-of-life as of 31 December 2023. Learn more about these deprecations and upgrading.

Custom scalars


The GraphQL specification includes default types Int, Float, String, Boolean, and ID. Although these s cover the majority of use cases, some applications need to support other atomic data types (such as Date) or add validation to an existing type. To enable this, you can define custom types.

Defining a custom scalar

To define a custom , add it to your like so:

scalar MyCustomScalar

s in your can now contain s of type MyCustomScalar. However, Apollo Server still needs to know how to interact with values of this new type.

Defining custom scalar logic

After you define a custom type, you need to define how Apollo Server interacts with it. In particular, you need to define:

  • How the 's value is represented in your backend
    • This is often the representation used by the driver for your backing data store.
  • How the value's back-end representation is serialized to a JSON-compatible type
  • How the JSON-compatible representation is deserialized to the back-end representation

You define these interactions in an instance of the GraphQLScalarType class.

For more information about the graphql library's type system, see the official documentation.

Example: The Date scalar

The following GraphQLScalarType object defines interactions for a custom that represents a date (this is one of the most commonly implemented custom scalars). It assumes that our backend represents a date with the Date JavaScript object.

const { GraphQLScalarType, Kind } = require('graphql');
const dateScalar = new GraphQLScalarType({
name: 'Date',
description: 'Date custom scalar type',
serialize(value) {
return value.getTime(); // Convert outgoing Date to integer for JSON
},
parseValue(value) {
return new Date(value); // Convert incoming integer to Date
},
parseLiteral(ast) {
if (ast.kind === Kind.INT) {
return new Date(parseInt(ast.value, 10)); // Convert hard-coded AST string to integer and then to Date
}
return null; // Invalid hard-coded value (not an integer)
},
});

This initialization defines the following methods:

  • serialize
  • parseValue
  • parseLiteral

Together, these methods describe how Apollo Server interacts with the in every scenario.

serialize

The serialize method converts the 's back-end representation to a JSON-compatible format so Apollo Server can include it in an response.

In the example above, the Date is represented on the backend by the Date JavaScript object. When we send a Date in a GraphQL response, we serialize it as the integer value returned by the getTime function of a JavaScript Date object.

Note that Apollo Client cannot automatically interpret custom s (see issue), so your client must define custom logic to deserialize this value as needed.

parseValue

The parseValue method converts the 's serialized JSON value to its back-end representation before it's added to a 's args.

Apollo Server calls this method when the is provided by a client as a GraphQL variable for an . (When a is provided as a hard-coded argument in the string, parseLiteral is called instead.)

parseLiteral

When an incoming query string includes the as a hard-coded value, that value is part of the query document's abstract syntax tree (AST). Apollo Server calls the parseLiteral method to convert the value's AST representation (which is always a string) to the 's back-end representation.

In the example above, parseLiteral converts the AST value from a string to an integer, and then converts from integer to Date to match the result of parseValue.

Providing custom scalars to Apollo Server

After you define your GraphQLScalarType instance, you include it in the same resolver map that contains s for your 's other types and s:

const { ApolloServer, gql } = require('apollo-server');
const { GraphQLScalarType, Kind } = require('graphql');
const typeDefs = gql`
scalar Date
type Event {
id: ID!
date: Date!
}
type Query {
events: [Event!]
}
`;
const dateScalar = new GraphQLScalarType({
// See definition above
});
const resolvers = {
Date: dateScalar
// ...other resolver definitions...
};
const server = new ApolloServer({
typeDefs,
resolvers
});

Example: Restricting integers to odd values

In this example, we create a custom called Odd that can only contain odd integers:

const { ApolloServer, gql } = require('apollo-server');
const { GraphQLScalarType, Kind } = require('graphql');
// Basic schema
const typeDefs = gql`
scalar Odd
type MyType {
oddValue: Odd
}
`;
// Validation function
function oddValue(value) {
return value % 2 === 1 ? value : null;
}
const resolvers = {
Odd: new GraphQLScalarType({
name: 'Odd',
description: 'Odd custom scalar type',
parseValue: oddValue,
serialize: oddValue,
parseLiteral(ast) {
if (ast.kind === Kind.INT) {
return oddValue(parseInt(ast.value, 10));
}
return null;
},
}),
};
const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`)
});

Importing a third-party custom scalar

If another library defines a custom , you can import it and use it just like any other symbol.

For example, the graphql-type-json package defines the GraphQLJSON object, which is an instance of GraphQLScalarType. You can use this object to define a JSON that accepts any value that is valid JSON.

First, install the library:

$ npm install graphql-type-json

Then require the GraphQLJSON object and add it to the map as usual:

const { ApolloServer, gql } = require('apollo-server');
const GraphQLJSON = require('graphql-type-json');
const typeDefs = gql`
scalar JSON
type MyObject {
myField: JSON
}
type Query {
objects: [MyObject]
}
`;
const resolvers = {
JSON: GraphQLJSON
// ...other resolvers...
};
const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`)
});
Previous
Unions and interfaces
Next
Directives
Edit on GitHubEditForumsDiscord