Add Nodes & Fields to GraphQL Schema

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.

🚀 TL;DR Show me the code. Look at the 13-asciidoc-conditional-content branch. This site is deployed here.

Action on Node Creation

The 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 slug field);
  • transforming content; or
  • linking nodes.

Creating a Raw Node

The 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 AsciidocRaw.

After this two new sections should be available in the GraphQL schema:

  • allAsciidocRaw and
  • AsciidocRaw.
GraphQL Explorer showing two new sections added to 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 createNodeField() function.

GraphQL Explorer showing new fields added to nodes.

Conclusion

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.