如何在GatsbyJS节点添加自定义GraphQL参数?

问题描述 投票:1回答:1

我创建了下面的盖茨比节点查询1项纪录

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);
      })
  );
};

我的源是休息的API,它的格式如下:

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

目前盖茨比节点默认ID集合为1

我可以做这个查询它在graphql:

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

这将始终返回记录1

我想添加自定义参数的ID,这样我可以做到这一点

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

我应该做我现有的代码什么调整?

javascript graphql gatsby
1个回答
1
投票

我假设你是creating page programmatically?如果是这样,在onCreatePage钩,当你做createPage,您可以在context对象传递。任何在那里将作为一个查询变量。

举例来说,如果你有

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

然后,你可以做一个网页查询像

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

如果你只是想通过编号进行筛选,你可以检查出filter & comparison operators的文档。

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

要么

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

希望能帮助到你!

© www.soinside.com 2019 - 2024. All rights reserved.