简体   繁体   中英

How to add a custom GraphQL parameter in a GatsbyJS node?

I created the following gatsby node to query 1 record

const axios = require("axios");

exports.sourceNodes = async (
  { actions, createNodeId, createContentDigest },
  configOptions
) => {
  const { createNode } = actions;

  // Gatsby adds a configOption that's not needed for this plugin, delete it
  delete configOptions.plugins;
  // Helper function that processes a post to match Gatsby's node structure
  const processPost = post => {
    const nodeId = createNodeId(`gutenberg-post-${post.id}`);
    const nodeContent = JSON.stringify(post);
    const nodeData = Object.assign({}, post, {
      id: nodeId,
      parent: null,
      children: [],
      internal: {
        type: `GutenbergPost`,
        content: nodeContent,
        contentDigest: createContentDigest(post)
      }
    });
    return nodeData;
  };

  const apiUrl = `http://wp.dev/wp-json/gutes-db/v1/${
    configOptions.id || 1
  }`;

  // Gatsby expects sourceNodes to return a promise
  return (
    // Fetch a response from the apiUrl
    axios
      .get(apiUrl)
      // Process the response data into a node
      .then(res => {
        // Process the post data to match the structure of a Gatsby node
        const nodeData = processPost(res.data);
        // Use Gatsby's createNode helper to create a node from the node data
        createNode(nodeData);
      })
  );
};

My source is a rest API that has the following format:

http://wp.dev/wp-json/gutes-db/v1/{ID}

Currently the gatsby node default ID set is 1

I can query it in graphql by doing this:

{
  allGutenbergPost {
    edges {
      node{
        data
      }
    }
  }
}

This will always return record 1

I wanted to add a custom parameter for ID so that I could do this

{
  allGutenbergPost(id: 2) {
    edges {
      node{
        data
      }
    }
  }
}

What adjustments should I do with my existing code?

I assume you are creating page programmatically ? If so, in the onCreatePage hook, when you do createPage , you can pass in a context object. Anything in there will be available as a query variable.

For example, if you have

createPage({
  path,
  component: blogPostTemplate,
  context: {
    foo: "bar",
  },
})

Then you can do a page query like

export const pageQuery = graphql`
  ExampleQuery($foo: String) {
    post(name: { eq: $foo }) {
      id
      content
    }
  }
`

If you just want to filter by id, you can check out the docs on filter & comparison operators .

{
  allGutenbergPost(filter: { id: { eq: 2 }}) {
    edges {
      node{
        data
      }
    }
  }
}

or

{
  gutenbergPost(id: { eq: 2 }) {
    data
  }
}

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM