如何使用过滤器定义和执行GraphQL查询
问题描述:
因此,我尝试做的事情是使用GraphQL从数据库(在我的情况下是MongoDB)中检索过滤的数据。如何使用过滤器定义和执行GraphQL查询
在“MySQL语言”中讲述如何在GraphQL中实现where
子句?
我遵循这个教程: 与滤波器https://learngraphql.com/basics/using-a-real-data-source/5
查询被这样定义:
const Query = new GraphQLObjectType({
name: "Queries",
fields: {
authors: {
type: new GraphQLList(Author),
resolve: function(rootValue, args, info) {
let fields = {};
let fieldASTs = info.fieldASTs;
fieldASTs[0].selectionSet.selections.map(function(selection) {
fields[selection.name.value] = 1;
});
return db.authors.find({}, fields).toArray();
}
}
}
});
这里棘手的部分是在resolve
功能的info
参数。几点说明我已经在这里找到:http://pcarion.com/2015/09/26/graphql-resolve/
所以这是AST(抽象语法树)
任何人都可以请提供一些基本的现实生活中的例子代码,将展示如何定义和执行的以下查询: 获取所有作者的名字==约翰
谢谢!
答
有没有必要检查AST。这将非常费力。
您只需要在author
字段中定义一个参数。这是解析器的第二个参数,因此您可以检查该争论并将其包含在Mongo查询中。
const Query = new GraphQLObjectType({
name: "Queries",
fields: {
authors: {
type: new GraphQLList(Author),
// define the arguments and their types here
args: {
name: { type: GraphQLString }
},
resolve: function(rootValue, args, info) {
let fields = {};
// and now you can check what the arguments' values are
if (args.name) {
fields.name = args.name
}
// and use it when constructing the query
return db.authors.find(fields, fields).toArray();
}
}
}
});
作为一个小概览什么其他过滤器/参数是可能的,这里是一个文章中,我们如何使用参数在Graphcool来实现过滤器:https://www.graph.cool/docs/tutorials/designing-powerful-apis -with-graphql查询参数,aing7uech3 – marktani