【发布时间】: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
}
}
}
}
我应该对现有代码进行哪些调整?
【问题讨论】:
-
使用新的模式自定义 API,您可以使用
createResolvers挂钩,然后您甚至不需要预先获取源代码,而是让查询决定返回什么 gatsbyjs.org/blog/2019-03-18-releasing-new-schema-customization/…
标签: javascript graphql gatsby