如何使用过滤器定义和执行GraphQL查询 [英] How to define and execute GraphQL query with filter

查看:106
本文介绍了如何使用过滤器定义和执行GraphQL查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想做的是使用GraphQL从数据库(在我的情况下为MongoDB)中检索经过过滤的数据.

So the thing i try to do is, retrieve filtered data from the Database (MongoDB in my situation) using GraphQL.

以"MySQL语言"来讲如何在GraphQL中实现 where 子句?

Speaking in "MySQL language" how to implement the where clause in GraphQL?

我遵循了本教程: https://learngraphql.com/basics/using-a-real-数据源/5

具有过滤器的查询的定义如下:

Query with filter was defined like this :

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/

The tricky part here is the info parameter in the resolve function. Some explanations i've found here : http://pcarion.com/2015/09/26/graphql-resolve/

因此它是 AST (抽象语法树)

So it is AST (Abstract Syntax Tree)

任何人都可以提供一些基本的实际示例代码,这些代码将显示如何定义执行以下查询:获取姓名== John的所有作者

Can anyone please provide some basic real-life example code that would show how to define and execute the following query : Get all authors where name == John

谢谢!

推荐答案

无需检查AST.那将非常费力.

There is no need to examine the AST. That would be awfully laborious.

您需要做的就是在 author 字段中定义一个参数.这是解析器的第二个参数,因此您可以检查该论点并将其包含在Mongo查询中.

All you need to do is define an argument on the author field. This is the second paramenter of the resolver, so you can check for that arguement and include it in the Mongo query.

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();
      }
    }
  }
});

这篇关于如何使用过滤器定义和执行GraphQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆