gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:50:35 25 4
gpt4 key购买 nike

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

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

最佳答案

我假设你是 creating page programmatically ?如果是这样,在 onCreatePage Hook 中,当您执行 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
}
}

希望对您有所帮助!

关于javascript - 如何在 GatsbyJS 节点中添加自定义 GraphQL 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54516858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com