【问题标题】:How to add a custom GraphQL parameter in a GatsbyJS node?如何在 GatsbyJS 节点中添加自定义 GraphQL 参数?
【发布时间】:2019-02-04 23:28:53
【问题描述】:

我创建了以下 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);
      })
  );
};

我的来源是一个具有以下格式的 REST 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
      }
    }
  }
}

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

【问题讨论】:

标签: javascript graphql gatsby


【解决方案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
    }
  }
`

如果您只想按 id 过滤,可以查看filter & comparison operators 上的文档。

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

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

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 2018-05-02
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    • 2021-02-06
    • 2014-01-26
    • 1970-01-01
    相关资源
    最近更新 更多