简体   繁体   English

GraphQL条件查询

[英]GraphQL Conditional Queries

I'm a newbie in GraphQL and I was wondering if there is a easy way to query with "dynamic conditions". 我是GraphQL的新手,我想知道是否有一种简单的方法来查询“动态条件”。

For exemple, on GraphiQL I can query for : 例如,在GraphiQL上我可以查询:

query {
  users{
    name
    age
  }
}

And It will bring me a list of all users 它将为我提供所有用户的列表

{
  "data": {
    "users": [
      {
        "name": "Luis Coimbra",
        "age": 15
      },
      {
        "name": "Sebastião Campagnucci",
        "age": 50
      },
      {
        "name": "Giovana Ribeiro",
        "age": 30
      }
    ]
  }
}

But is there an easy way for me to bring only, for example, users who are above 18 or any other age ? 但是,对于我来说,只有18岁以上或任何其他年龄的用户才能轻松获得?

An expected solution would be: 预期的解决方案是:

query {
      users{
        name
        age > 18
      }
    }

Haven't found anything like that on documentation... 在文档上没有找到类似的东西......

This is possible-it would have to be different. 这是可能的 - 它必须是不同的。 Your query wouldn't be a valid GQL query. 您的查询将不是有效的GQL查询。 Something like this would: 这样的事情会:

    {
      users(where: {age: { $gt: 18 }}){ #inspired by mongoDB query api
        name
        age
      }
    }

or maybe simpler: 或者更简单:

   {
     users(where: {age: ">18"}}){
        name
        age
      }
   }

of course either way the resolver on the backend needs to expect this where argument on the users field and construct the DB query accordingly when it is passed. 当然,后端的解析器需要在users字段的参数上进行预期where并在传递时相应地构造数据库查询。 You would not find this in GraphQL docs because GraphQL itself doesn't care about that. 你不会在GraphQL文档中找到它,因为GraphQL本身并不关心它。 It only showcases how to use features of GraphQL. 它只展示了如何使用GraphQL的功能。

If you tried example projects like for example star was api, those don't have any filtering built in. 如果您尝试了示例项目,例如star是api,则那些内置的过滤器没有。

You should send your age filter as a parameter.You might try the following one: 您应该将年龄过滤器作为参数发送。您可以尝试以下方法:

In your graphql file 在你的graphql文件中

type users {
 name: String,
 age: Int,
 ...
}

usersQuery(ageLimit: Int): [users]

also you can send '>' , '<' , '=' as a parameter. 你也可以发送'>','<','='作为参数。 Also it seems like that 它似乎也是这样

usersQuery(ageLimit: Int, ageOperator: String): [users]

and you should configure your resolver where statement with these operators. 并且您应该使用这些运算符配置解析器where语句。 hope it helps you. 希望它能帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM