如何使用过滤器定义和执行GraphQL查询

时间:2017-04-14 18:43:22

标签: graphql

所以我尝试做的是使用GraphQL从数据库(在我的情况下使用MongoDB)中检索过滤数据。

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

这里棘手的部分是info函数中的resolve参数。我在这里找到了一些解释:http://pcarion.com/2015/09/26/graphql-resolve/

所以它是AST(抽象语法树)

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

谢谢!

1 个答案:

答案 0 :(得分:2)

无需检查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();
      }
    }
  }
});
相关问题