Gatsby Node Helpers

1.2.1 · active · verified Tue Apr 21

The `gatsby-node-helpers` package provides a set of utility functions specifically designed to simplify and streamline the process of creating Gatsby nodes within source plugins. Its current stable version is 1.2.1. While not adhering to a strict time-based release cadence, the project actively publishes updates, with recent releases addressing feature enhancements and minor adjustments. It differentiates itself by abstracting away the complexities of Gatsby's internal node requirements, such as automatically generating `contentDigest`, handling Gatsby's reserved field conflicts through intelligent namespacing, and providing compliant functions for generating type names and unique IDs. This significantly streamlines the development of Gatsby source plugins by ensuring created nodes adhere to Gatsby's internal data model, reducing boilerplate and common errors associated with manual node creation in `gatsby-node.js` files.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates initializing `createNodeHelpers` and using `createNodeFactory` to prepare product data for Gatsby's `createNode` action within the `sourceNodes` API.

import * as gatsby from 'gatsby'
import { createNodeHelpers } from 'gatsby-node-helpers'

interface MyProduct {
  id: string;
  name: string;
  price: number;
}

// Simulate fetching product data
async function getAllProducts(): Promise<MyProduct[]> {
  return [
    { id: 'p1', name: 'Product A', price: 29.99 },
    { id: 'p2', name: 'Product B', price: 49.99 }
  ]
}

export const sourceNodes: gatsby.GatsbyNode['sourceNodes'] = async (
  gatsbyArgs: gatsby.SourceNodesArgs,
) => {
  const { actions, createNodeId, createContentDigest } = gatsbyArgs
  const { createNode } = actions

  const nodeHelpers = createNodeHelpers({
    typePrefix: 'MyPlugin',
    createNodeId,
    createContentDigest,
  })

  const ProductNode = nodeHelpers.createNodeFactory<MyProduct>('Product')

  const products = await getAllProducts()

  for (const product of products) {
    const node = await ProductNode(product)
    // `node` now contains all the fields required by `createNode`
    // (e.g., id, parent, children, internal.contentDigest, internal.type, etc.)

    createNode(node)
  }
}

view raw JSON →