Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Custom Scalars in GraphQL

1. Introduction

GraphQL allows you to define your own custom scalar types, which can be used to represent data types that are not natively supported by GraphQL, such as dates, URLs, or any complex data structure.

2. What are Custom Scalars?

Custom scalars are user-defined types in GraphQL that extend the default scalars (Int, Float, String, Boolean, ID). They enable you to define a specific shape and validation for your data.

Note: Custom scalars are especially useful for complex data validation that cannot be achieved using the default scalars.

3. Defining Custom Scalars

To define a custom scalar in GraphQL, you need to implement two main functions: serialize and parseValue. Below is an example of a custom scalar for a date.

const { GraphQLScalarType } = require('graphql');

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

module.exports = DateScalar;

4. Using Custom Scalars

Once defined, you can utilize your custom scalar type in your schema as follows:

const { GraphQLObjectType, GraphQLSchema } = require('graphql');
const DateScalar = require('./DateScalar');

const UserType = new GraphQLObjectType({
    name: 'User',
    fields: () => ({
        id: { type: GraphQLID },
        createdAt: { type: DateScalar },
    })
});

const schema = new GraphQLSchema({
    query: UserType,
});

module.exports = schema;

5. Best Practices

  • Ensure your custom scalar has a clear purpose and validation logic.
  • Document the expected format for clients consuming your API.
  • Keep the implementation consistent across your application.
  • Consider using libraries for complex types (e.g., `graphql-scalars`).

6. FAQ

What are the benefits of using custom scalars?

Custom scalars provide flexibility in defining complex data types and ensure that data validation is handled correctly at the GraphQL layer.

Can I use multiple custom scalars in one schema?

Yes, you can define and use multiple custom scalars within a single GraphQL schema.

How do I handle errors in custom scalars?

Implement error handling in your custom scalar functions to ensure that invalid data types are communicated properly to the client.