0
0
GraphqlConceptBeginner · 3 min read

What is Custom Scalar Type in GraphQL: Explanation and Example

A custom scalar type in GraphQL is a user-defined data type that extends the built-in scalar types like String or Int. It allows you to define how to serialize, parse, and validate specific data formats that don't fit standard types, such as dates or complex IDs.
⚙️

How It Works

Think of a custom scalar type as a special box you create to hold a unique kind of data that GraphQL doesn't understand by default. Just like you might have a special container for fragile items in real life, a custom scalar tells GraphQL how to handle data that needs special care.

When you define a custom scalar, you provide rules for how to turn that data into a string to send over the network (serialization), how to read it back into your program (parsing), and how to check if the data is valid (validation). This way, GraphQL knows exactly what to do with your custom data type during queries and mutations.

💻

Example

This example shows how to create a custom scalar type called Date that handles date strings in ISO format.

javascript
const { GraphQLScalarType, Kind } = require('graphql');

const DateScalar = new GraphQLScalarType({
  name: 'Date',
  description: 'Custom scalar type for dates in ISO format',
  serialize(value) {
    // Convert outgoing Date object to ISO string
    return value instanceof Date ? value.toISOString() : null;
  },
  parseValue(value) {
    // Convert incoming ISO string to Date object
    return new Date(value);
  },
  parseLiteral(ast) {
    if (ast.kind === Kind.STRING) {
      return new Date(ast.value);
    }
    return null; // Invalid hard-coded value
  },
});

module.exports = { DateScalar };
🎯

When to Use

Use custom scalar types when you need to handle data that doesn't fit into GraphQL's built-in types like String, Int, or Boolean. Common examples include dates, timestamps, URLs, email addresses, or even complex IDs.

For instance, if your app works with dates, a custom Date scalar ensures all dates are consistently formatted and validated. This helps avoid errors and keeps your API clear and reliable.

Key Points

  • Custom scalars extend GraphQL's built-in scalar types.
  • They define how to serialize, parse, and validate custom data.
  • Useful for special data like dates, URLs, or IDs.
  • Improve API clarity and data consistency.

Key Takeaways

Custom scalar types let you define how special data is handled in GraphQL.
They require you to specify serialization, parsing, and validation logic.
Use them for data formats not covered by default scalars, like dates or URLs.
Custom scalars help keep your API data consistent and clear.