Schema Inference

Each time a node is created, yielding a newly sourced or transformed node, Gatsby generates inference metadata that can be merged with other metadata such that it’s possible to define a schema for the new node that is as specific as possible to its structure. Thanks to inference metadata, Gatsby can also understand if there are any conflicts in the data and display a warning to the user. The process by which Gatsby adds to the schema it creates based on this metadata is known as schema inference.

To do this, Gatsby creates a GraphQLObjectType, or gqlType, for each unique node.internal.type field value that is encountered during the node sourcing phase. In Gatsby, each gqlType is an object that defines both the type name and each of the fields contained therein, which are provided by the createNodeFields function in Gatsby’s internal src/schema/build-node-types.js file.

Each gqlType object is created before its fields are inferred, allowing for fields to be introduced later when their types are created. This is achieved in Gatsby through the use of lazy functions in the same build-node-types.js file.

Once the gqlType is created, Gatsby can begin to infer fields. The first thing it does is generate an exampleValue, which is the result of merging together all the fields from all the nodes of that gqlType. As such, this exampleValue variable will house all prospective field names and their values, allowing Gatsby to infer each field’s type. This logic occurs in the getExampleValues function in src/schema/data-tree-utils.js.

There are three types of fields that Gatsby makes available in each node it creates by inferring the type’s fields based on the exampleValue:

  1. Fields on the created Node object
  2. Child and parent relationship fields
  3. Fields created by setFieldsOnGraphQLNodeType

Let’s take a look at the first two of these. The third type of inferred field, created by plugins that implement the setFieldsOnGraphQLNodeType API, requires those plugins to return full GraphQL field declarations, including type and resolver functions.


Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *