如何使用过滤器定义和执行GraphQL查询
因此,我尝试使用GraphQL从数据库(在我的情况下是MongoDB)检索过滤后的数据 用“MySQL语言”讲,如何在GraphQL中实现如何使用过滤器定义和执行GraphQL查询,graphql,Graphql,因此,我尝试使用GraphQL从数据库(在我的情况下是MongoDB)检索过滤后的数据 用“MySQL语言”讲,如何在GraphQL中实现where子句 我遵循了本教程: 使用筛选器的查询定义如下: const Query = new GraphQLObjectType({ name: "Queries", fields: { authors: { type: new GraphQLList(Author), resolve: function(root
where
子句
我遵循了本教程:
使用筛选器的查询定义如下:
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
参数。我在这里找到了一些解释:
就是这样(抽象语法树)
任何人都可以提供一些基本的实际示例代码,说明如何定义和执行以下查询:
获取name==John的所有作者
谢谢大家! 无需检查AST。这将是非常费力的 您只需在
作者
字段中定义一个参数。这是解析器的第二个参数,因此您可以检查该参数并将其包含在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();
}
}
}
});
作为对其他可能的过滤器/参数的一点概述,下面是一篇如何在GraphTool中使用参数实现过滤器的文章:这是我关于可以添加到GraphQL API的灵活过滤功能的文章。所有这些,同时保持我们从GraphQL中获得的类型安全性和运行时验证。