Unknown Type Date In GraphQL Schema
GraphQL
09/01/2023
If you get an error ❌ similar to this,
BASH
Failed to load schema from graphql/schema.ts: Unknown type: "Date".
it means your scalar type Date
has not been defined. Natively, GraphQL only supports 6 types out of the box:
Int
Float
String
Boolean
ID
As a result, any other types need to be defined by the developer themselves.
Creating a custom scalar type
A scalar type Date
is quite common. To use one, first define the new scalar type in your GraphQL schema.
GRAPHQL
scalar Date
Next, GraphQL needs to know 🧠 how to treat this type. For that, the GraphQLScalarType
class is to be used. You should pay attention to the following methods:
serialize
- How the data should be converted from its back-end representation (i.e. the JavaScriptDate
type) to a JSON-compatible format for network requests.parseValue
- How the data should be reverted from its serialized form to back-end representation.parseLiteral
- How the data should be treated if it's hardcoded in an incoming query. It's helpful to know that this hardcoded value is part of the query document's (i.e. query graph) abstract syntax tree 🌳 (AST).
JAVASCRIPT
import { GraphQLScalarType, Kind } from "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) { // Convert hard-coded AST string to integer and then to Date return new Date(parseInt(ast.value, 10)) } // Invalid hard-coded value (not an integer) return null },})
Lastly, add the custom scalar type in your resolvers, so GraphQL has access to its definition.
JAVASCRIPT
const resolvers = { Date: dateScalar, //...}