Advertisement
Intermediate Node.js, GraphQL

What is the difference between a GraphQL scalar type and an object type, and how would you define a custom scalar (like DateTime) in a Node.js GraphQL server?

Short answer

Scalar types represent primitive, leaf-level values (the built-in ones are Int, Float, String, Boolean, and ID) that can't have their own sub-fields queried, while object types represent structured data with their own set of fields that can themselves be queried further --…

Save Node.js mock interview
Advertisement
AModel answer
Scalar types represent primitive, leaf-level values (the built-in ones are Int, Float, String, Boolean, and ID) that can't have their own sub-fields queried, while object types represent structured data with their own set of fields that can themselves be queried further -- GraphQL also supports custom scalars for domain-specific primitive values not covered by the built-ins (like a properly-validated DateTime or Email), implemented by providing serialize, parseValue, and parseLiteral functions that define how that custom type converts between its internal representation and the wire format.
const { GraphQLScalarType } = require('graphql');

const DateTimeScalar = new GraphQLScalarType({
  name: 'DateTime',
  serialize: (value) => value.toISOString(),
  parseValue: (value) => new Date(value),
});

const resolvers = { DateTime: DateTimeScalar, /* ... */ };
Real-world example
An events API defines a custom DateTime scalar to properly serialize and parse date values consistently as ISO 8601 strings across the entire schema, rather than representing timestamps as plain, ambiguous strings or numbers that each client might interpret differently.
Likely follow-ups
  • What validation or parsing errors should a custom scalar's parseValue function raise if given genuinely invalid input?
  • Are there well-maintained community packages providing common custom scalars like DateTime and JSON, rather than implementing them from scratch?
Related topics