首页 > 解决方案 > 如何在 GatsbyJS 节点中添加自定义 GraphQL 参数?

问题描述

我创建了以下 gatsby 节点来查询 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}

目前 gatsby 节点默认 ID 设置为 1

我可以通过这样做在graphql中查询它:

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

这将始终返回记录 1

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

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

我应该对现有代码进行哪些调整?

标签: javascriptgraphqlgatsby

解决方案


我假设您正在以编程方式创建页面?如果是这样,在onCreatePage钩子中,当你这样做时createPage,你可以传入一个context对象。里面的任何东西都可以作为查询变量使用。

例如,如果您有

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

然后你可以做一个页面查询,比如

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

如果您只想按 id 过滤,您可以查看有关过滤器和比较运算符的文档。

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

或者

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

希望能帮助到你!


推荐阅读