It’s useful to be able to add fields to the GraphQL schema. In this post I’ll illustrate how to do this by adding nodes for the raw AsciiDoc source and linking the raw data to the processed content.
Action on Node Creation
onCreateNode() function in
gatsby-node.js is used to manipulate or extend Gatsby nodes. Gatsby creates a node for each piece of content. The
onCreateNode() function is called every time a node is created. Typical use cases are:
- adding fields (we’re already using it to add a
- transforming content; or
- linking nodes.
Creating a Raw Node
onCreateNode() function receives a node as an argument. We can use the
parent field on that node to generate the path to the corresponding AsciiDoc source. Then we read in the source content.
Having the raw AsciiDoc content we then create an object with all of the required fields for a GraphQL node. We include a
content field which contains the raw AsciiDoc. The use the
createNode() function to create a new node of type
After this two new sections should be available in the GraphQL schema:
Add Custom Field
We now have nodes for the raw AsciiDoc data. However, we’d ideally want to link the processed content to the raw data too. In order to do this we’ll add a custom field to each of the
Asciidoc fields using the
We have used two functions to add content to the GraphQL schema:
createNode()— add a new node; and
createNodeField()— add a field to an existing node.