GraphQL fields can handle scalar values—namely String
, Date
, ID
, Int
, Float
, Boolean
, and JSON
—but fields can also contain complex values in the form of objects. To handle these nested fields, we need to provide an explicit type definition for the nested type. For instance, we may wish to ensure that each MarkdownRemark
(Markdown document) Node
contains a frontmatter
field known as frontmatter.translations
that itself is a list of strings:
// gatsby-node.js
exports
.
createSchemaCustomization
=
({
actions
})
=>
{
const
{
createTypes
}
=
actions
const
typeDefs
=
`
type MarkdownRemark implements Node {
frontmatter: Frontmatter
}
type Frontmatter {
translations: [String!]!
}
`
createTypes
(
typeDefs
)
}
Note that because we are specifying the Frontmatter
type for the first time using this createTypes
action, we cannot simply supply a bare Frontmatter
definition without accounting for it in the overarching MarkdownRemark
type—without that, GraphQL will have no awareness of the Frontmatter
field. For this reason, Gatsby recommends as a best practice beginning from the standpoint of the types generated by source and transformer plugins when writing type definitions.
NOTE
Though GraphQL’s SDL provides a sufficiently concise way to author type definitions that customize the schema, the createTypes
action also allows for type definitions that use Gatsby Type Builders, which can offer more leeway than SDL syntax and result in less verbosity than direct implementations of graphql-js
. For more information about foreign key fields, default field values, and available extensions and directives, consult the Gatsby documentation’s sections on foreign key fields, extensions and directives, setting default field values, and creating custom extensions.
Leave a Reply