Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/461.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在GatsbyJS节点中添加自定义GraphQL参数?_Javascript_Graphql_Gatsby - Fatal编程技术网

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

Javascript 如何在GatsbyJS节点中添加自定义GraphQL参数?,javascript,graphql,gatsby,Javascript,Graphql,Gatsby,我创建了以下gatsby节点来查询1条记录 const axios=require(“axios”); exports.sourceNodes=async( {actions,createNodeId,createContentDigest}, 配置选项 ) => { const{createNode}=操作; //盖茨比添加了这个插件不需要的配置选项,删除它 删除configOptions.plugins; //处理post以匹配盖茨比节点结构的辅助函数 const processPost=p

我创建了以下gatsby节点来查询1条记录

const axios=require(“axios”);
exports.sourceNodes=async(
{actions,createNodeId,createContentDigest},
配置选项
) => {
const{createNode}=操作;
//盖茨比添加了这个插件不需要的配置选项,删除它
删除configOptions.plugins;
//处理post以匹配盖茨比节点结构的辅助函数
const processPost=post=>{
const nodeId=createNodeId(`gutenberg post-${post.id}`);
const nodeContent=JSON.stringify(post);
const nodeData=Object.assign({},post{
id:nodeId,
父项:null,
儿童:[],
内部:{
类型:`GutenbergPost`,
内容:nodeContent,
contentDigest:createContentDigest(post)
}
});
返回nodeData;
};
常量apiUrl=`http://wp.dev/wp-json/gutes-db/v1/${
configOptions.id | | 1
}`;
//盖茨比希望sourceNodes返回一个承诺
返回(
//从APIRL获取响应
axios
.get(apirl)
//将响应数据处理到节点中
。然后(res=>{
//处理post数据以匹配Gatsby节点的结构
const nodeData=processPost(res.data);
//使用Gatsby的createNode帮助器从节点数据创建节点
createNode(nodeData);
})
);
};
我的源代码是具有以下格式的rest API:

http://wp.dev/wp-json/gutes-db/v1/{ID}
目前,盖茨比节点的默认ID设置为1

我可以通过以下操作在graphql中查询它:

{
  allGutenbergPost {
    edges {
      node{
        data
      }
    }
  }
}
这将始终返回记录1

我想为ID添加一个自定义参数,以便可以这样做

{
  allGutenbergPost(id: 2) {
    edges {
      node{
        data
      }
    }
  }
}
我应该如何调整我现有的代码?

我想你是这样的吧?如果是这样,在
onCreatePage
钩子中,当您执行
createPage
操作时,可以传入
上下文
对象。其中的任何内容都可以作为查询变量使用

例如,如果你有

createPage({
  path,
  component: blogPostTemplate,
  context: {
    foo: "bar",
  },
})
然后您可以执行如下页面查询

export const pageQuery = graphql`
  ExampleQuery($foo: String) {
    post(name: { eq: $foo }) {
      id
      content
    }
  }
`

如果您只想按id筛选,您可以在上签出文档


希望有帮助

使用新的模式定制API,您可以使用
createResolvers
hook,这样您甚至不需要预先获取源代码,而是让查询决定返回什么
{
  allGutenbergPost(filter: { id: { eq: 2 }}) {
    edges {
      node{
        data
      }
    }
  }
}
{
  gutenbergPost(id: { eq: 2 }) {
    data
  }
}