【问题标题】:How to define and execute GraphQL query with filter如何使用过滤器定义和执行 GraphQL 查询
【发布时间】:2017-09-11 01:22:39
【问题描述】:

所以我尝试做的是,使用 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();
      }
    }
  }
});

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

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

任何人都可以提供一些基本的真实示例代码来展示如何定义执行以下查询: 获取 name == John 的所有作者

谢谢!

【问题讨论】:

    标签: graphql


    【解决方案1】:

    无需检查 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 上使用参数来实现过滤器:graph.cool/docs/tutorials/…
    • 这是我关于可以添加到 GraphQL API 的灵活过滤功能的文章。所有这一切同时保持我们从 GraphQL 开箱即用的类型安全和运行时验证。 dev.to/mgustus/…
    猜你喜欢
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 2018-05-31
    • 2017-05-16
    • 1970-01-01
    相关资源
    最近更新 更多