javascript - 如何在 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
}
}
}
}
我应该对现有代码进行哪些调整?
解决方案
我假设您正在以编程方式创建页面?如果是这样,在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
}
}
希望能帮助到你!
推荐阅读
- c++ - 无法通过 UDP 发送数据
- javascript - 当我使用 angularjs 在元素中使用 ng-click 时,$watch 不会触发
- neural-network - 如何使用 PyTorch 计算神经网络中输入的输出梯度?
- php - 带有 PHP 和 MYSQL 的响应式垂直多级菜单
- ios - 将滑块值设置为文本视图中的当前读取位置
- javascript - 如何使用 { 对列表进行分组
- php - SparkPost 电子邮件不起作用
- c++ - 功能延迟时计时器停止
- java - spring security csrf禁用问题
- perl - 如何在 Windows 上运行带有 CGI 的便携式 Perl?