Connecting two gatsby nodes

后端 未结 1 371
长发绾君心
长发绾君心 2021-01-02 21:07

So, I\'m using the gatsby-mdx plugin to create a site from MDX files. I want to create an association between the SitePage object and the Mdx object so that I can do one gra

1条回答
  •  自闭症患者
    2021-01-02 21:48

    So I finally found a better solution (than my previous attempt, which involves pumping mdx node into page’s context).

    Gatsby has a undocumented method to link nodes to one another:

    Yes, you can can use createNodeField with the not-yet-documented ___NODE syntax to create links between nodes.

    So, the steps are like this:

    • In createPage, store the id of the Mdx node to SitePage node.
    • In onCreateNode, if node is SitePage, use createNodeField with the Mdx___NODE as field name and Mdx node's id as value.

    My gatsby-node.js:

    const path = require("path")
    const { createFilePath } = require("gatsby-source-filesystem")
    
    exports.onCreateNode = ({ node, actions, getNode }) => {
      const { createNodeField } = actions
    
      if (node.internal.type === "SitePage" && node.context && node.context.id) {
    
        createNodeField({
          name: "Mdx___NODE",
          value: node.context.id,
          node,
        })
      }
    
      if (node.internal.type === "Mdx") {
        const value = createFilePath({ node, getNode })
        createNodeField({
          // 1) this is the name of the field you are adding,
          name: "slug",
          // 2) this node refers to each individual MDX
          node,
          value: `/blog${value}`
        })
      }
    }
    
    
    exports.createPages = async ({ graphql, actions }) => {
      const { createPage } = actions;
      const { data, errors } = await graphql(`
        {
          allMdx {
            edges {
              node {
                id
                fields {
                  slug
                }
              }
            }
          }
        }
      `)
    
      if (errors) throw errors
      data.allMdx.edges.forEach(({ node }) => {
        createPage({
          path: node.fields.slug,
          component: path.resolve(`./src/components/posts-page-layout.js`),
          context: { id: node.id }
        });
      });
    };
    

    Result:

    Hope it helps!

    0 讨论(0)
提交回复
热议问题