GraphQL将参数传递到子解析
我在用户和帖子之间有一种关系。这就是我查询用户帖子的方式GraphQL将参数传递到子解析,graphql,graphql-js,Graphql,Graphql Js,我在用户和帖子之间有一种关系。这就是我查询用户帖子的方式 const UserType = new GraphQLObjectType({ name: 'User' fields: () => ({ name: { type: GraphQLString }, posts: { type: new GraphQLList(PostType), resolve(parent, args , { db }) {
const UserType = new GraphQLObjectType({
name: 'User'
fields: () => ({
name: {
type: GraphQLString
},
posts: {
type: new GraphQLList(PostType),
resolve(parent, args , { db }) {
// I want to get here the args.someBooleanArg
return someLogicToGetUserPosts();
}
}
})
});
主要查询是:
const queryType = new GraphQLObjectType({
name: 'RootQuery',
fields: {
users: {
type: new GraphQLList(UserType),
args: {
id: {
type: GraphQLInt
},
someBooleanArg: {
type: GraphQLInt
}
},
resolve: (root, { id, someBooleanArg }, { db }) => {
return someLogicToGetUsers();
}
}
}
});
问题是UserType posts的resolve函数中的args为空对象,如何将args从主查询传递到子resolve函数?解析根查询时,可以使用object assign将参数附加到返回的用户对象。 然后,在用户类型上,从根值解析参数(resolve函数的第一个参数) 例如:
const queryType=new GraphQLObjectType({
名称:“RootQuery”,
字段:{
用户:{
类型:新的GraphQList(用户类型),
args:{
身份证:{
类型:GraphQLInt
},
一些布尔语:{
类型:GraphQLInt
}
},
解析:(root,{id,someBooleanArg},{db})=>{
返回Promise.resolve(someLogicToGetUsers())。然后(v=>{
返回Object.assign({},v{
一些布尔人
});
});
}
}
}
});
const UserType=新的GraphQLObjectType({
名称:“用户”
字段:()=>({
姓名:{
类型:GraphQLString
},
职位:{
类型:新的GraphQList(PostType),
解析(父,参数,{db}){
console.log(parent.someBooleanArg);
返回someLogicToGetUserPosts();
}
}
})
});
您可以使用解析器第四个参数,info
,从Apollo文档接收所需变量:
GraphQL.js架构中的每个解析器都接受四个位置参数:
字段名(对象、参数、上下文、信息)
{result}
这些论据已经过时
以下含义和常规名称:
obj:包含上的冲突解决程序返回的结果的对象
父字段,如果是顶级查询字段,则为
从服务器配置传递的rootValue。此参数使
GraphQL查询的嵌套性质
args:具有
参数传递到查询中的字段中。例如,如果
字段是用author(名称:“Ada”)调用的,args对象是:{
“名称”:“Ada”}
上下文:这是中所有解析程序共享的对象
一个特定的查询,用于包含每个请求的状态,
包括身份验证信息、数据加载程序实例和
解决问题时应考虑的其他事项
查询如果您使用的是Apollo Server,请阅读有关如何设置
设置文档中的上下文
信息:此参数应为
用于高级情况,但它包含有关
查询的执行状态,包括字段名、到
来自根的字段,等等。它只记录在GraphQL.js中
源代码
info
似乎是一个非常没有文档记录的功能,但我现在使用它没有任何问题(至少在有人决定更改它之前)
这里是诀窍:
const UserType = new GraphQLObjectType({
name: 'User'
fields: () => ({
name: {
type: GraphQLString
},
posts: {
type: new GraphQLList(PostType),
resolve(parent, args , { db }, info) {
// I want to get here the args.someBooleanArg
console.log("BINGO!");
console.log(info.variableValues.someBooleanArg);
return someLogicToGetUserPosts();
}
}
})
});
是否没有本机方法将其作为“args”传递到子查询,而不是更改响应对象?这是不正确的,字段的
args
与查询的变量不同。例如,您可以有``query($variableId:ID){user(ID:$variableId){posts{//这里您可以得到info.variableValues.variableId,而不是user args.ID}``这只适用于命名变量,如果您使用硬编码的变量,它们不会显示出来