我创建了以下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
}
}
}
}
我应该对现有代码进行哪些调整?
答案 0 :(得分: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
}
}
希望有帮助!