To get started with GraphQL Scalars, install the packages as follows:
npm i graphql-scalars
yarn add graphql-scalars
pnpm add graphql-scalars
bun add graphql-scalars
Integration to your Existing GraphQL Schema
GraphQL Scalars is easy to integrate into your existing GraphQL Schema. You need to add a scalar
definition to your SDL type definitions and resolvers like below;
In your SDL Type Definitions
schema.graphql
scalar ScalarName
You can also import ready-to-use type definitions for scalars like below:
// or import specific typeDefs only with ES6 Import// or import all typeDefs once with ES6 Importimport { ScalarNameTypeDefinition, typeDefs as scalarTypeDefs } from 'graphql-scalars'// or import specific typeDefs only with CommonJSconst { ScalarNameTypeDefinition } = require('graphql-scalars')// or import all typeDefs once with CommonJSconst { typeDefs: scalarTypeDefs } = require('graphql-scalars')const typeDefs = [ ...scalarTypeDefs // other typeDefs]// orconst typeDefs = [ ScalarNameTypeDefinition // other typeDefs]
Importing it into your Resolver Map
You can either import the specific scalar’s resolvers or all of the resolvers once.
// or import specific resolvers only with ES6 Import// or import all resolvers once with ES6 Importimport { ScalarNameResolver, resolvers as scalarResolvers } from 'graphql-scalars'// or import specific resolvers only with CommonJSconst { ScalarNameResolver } = require('graphql-scalars')// or import all resolvers once with CommonJSconst { resolvers: scalarResolvers } = require('graphql-scalars')
Adding to the Root Resolver Map
const myResolverMap = { ScalarName: ScalarNameResolver, Query: { // more stuff here }, Mutation: { // more stuff here }}
Using it in your Type Definitions
That’s it. Now you can use these scalar types in your schema definition like this: