Many nodes have a relationship to a parent node or child node that establishes a dependency between the two. Gatsby’s build process provides several approaches to create these relationships, which isn’t straightforward due to the fact that all nodes are considered top-level objects in the Redux nodes
namespace. For this reason, each node’s children
field consists of an array of node identifiers, each pointing to a node at the same level in that Redux namespace, as seen in the following example:
{
`id1`: { type: `File`, children: [`id2`, `id3`], ...other_fields },
`id2`: { type: `markdownRemark`, ...other_fields },
`id3`: { type: `postsJson`, ...other_fields }
}
In Gatsby, all children are stored within a single collection having parent references.
Certain child nodes need to have their relationships to their parent explicitly defined. This is most often the case when nodes are transformed from other nodes through onCreateNode
implementations, thereby establishing a relationship between the untransformed parent node and the transformed child node (or a previously transformed parent node in the case of consecutive transformations). For instance, transformer plugins often implement onCreateNode
to create a child node, as we saw in Section 9, invoking createParentChildLink
in the process. This function call pushes the transformed child node’s identifier to the parent’s children
collection and commits it to Redux.
WARNING
This unfortunately doesn’t automatically facilitate the creation of a parent field on the child node. Plugin authors, such as those writing transformer plugins, who wish to permit access to child nodes’ parents within the context of GraphQL queries need to explicitly write childNode.parent: `parent.id`
when creating the child node.
The definition of child nodes as node identifiers within the top level of the Redux nodes
namespace also drives what is known as foreign key references, which are used in GraphQL to access child nodes from the standpoint of the parent node. The names of foreign key fields accessing these foreign keys are suffixed with ___NODE
. When Gatsby runs the GraphQL queries for pages and components, it adopts that value as an identifier and searches the Redux nodes
namespace for the matching node. We’ll come back to this process when we turn to schema generation.
NOTE
For more information about how Gatsby handles plain objects as nodes during the node creation phase, consult the documentation.
Leave a Reply