For this reason, it can often be preferable to create type definitions manually, explicitly defining types so that Gatsby can validate the field and inform you if there is malformed data, such as an invalid Date
. Through the createSchemaCustomization
Node API, Gatsby provides a means for developers to supply the GraphQL schema with explicit type definitions in gatsby-node.js using the createTypes
action, which accepts as inputs type definitions written in GraphQL’s SDL:
// gatsby-node.js
exports
.
createSchemaCustomization
=
({
actions
})
=>
{
const
{
createTypes
}
=
actions
const
typeDefs
=
`
type AuthorJson implements Node {
created: Date
}
`
createTypes
(
typeDefs
)
}
Thanks to Gatsby’s automatic type inference capability, there is no need for us to also provide explicit type definitions for the other field types, unless we wish to. Nevertheless, there are situations where providing an unabridged type definition may be preferable, in the process opting out of Gatsby’s automatic type inference. This is especially the case for larger Gatsby sites working with substantial amounts of data where type inference begins to detrimentally impact performance.
The @dontInfer
type directive in Gatsby can be used to opt out of automatic type inference for a field, but the catch is that you must provide all type definitions explicitly for that field to be made available for querying via the GraphQL API. For example, opting out of automatic type inference for the AuthorJson
type would mean that we would need to provide a full type definition:
// gatsby-node.js
exports
.
createSchemaCustomization
=
({
actions
})
=>
{
const
{
createTypes
}
=
actions
const
typeDefs
=
`
type AuthorJson implements Node @dontInfer {
name: String!
firstName: String!
email: String!
created: Date
}
`
createTypes
(
typeDefs
)
}
Note that Gatsby’s internal Node
interface fields (id
, parent
, children
, internal
) are automatically created by Gatsby and don’t require inclusion in the unabridged type definition.
TIP
There are several extensions available in GraphQL type definitions that can be used to specify the media types that are acceptable and child relations that need to be established with a parent type. For more information about these, consult the Gatsby documentation’s sections on defining media types and child relations.
Leave a Reply