如何有条件地在 GraphQL 查询中包含过滤参数? [英] How to conditionally include a filtering argument in a GraphQL query?

查看:52
本文介绍了如何有条件地在 GraphQL 查询中包含过滤参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 GraphQL 查询(使用 Apollo Client JS):

I have the following GraphQL query (using Apollo Client JS):

query GetUsers($searchFilter: String) {
    users(
        first: 10,
        filter: { search: $searchFilter }
    ) {
        nodes {
            id
            name
        }
    }
}

当我传入 $searchFilter 参数时,这很有效.但是,我希望这个 $searchFilter 参数是可选.所以当它是 null 时,它不会应用过滤器.

This works well when I pass in the $searchFilter argument. However, I want this $searchFilter argument to be optional. So when it's null it doesn't apply the filter.

这看起来很简单,但 API 要求 search 不可为空.所以传入 filter: { search: null } 是不允许的.

This seems simple enough, but the API requires the search to be non-nullable. So passing in filter: { search: null } is not allowed.

我想实现以下目标:

query GetUsers($searchFilter: String) {
    users(
        first: 10,
        filter: $searchFilter = null ? null : { search: $searchFilter }
    ) {
        nodes {
            id
            name
        }
    }
}

如何有条件地包含 filter 参数?

How do I conditionally include the filter argument?

推荐答案

只需为 filter(在查询中定义)变量传递(整个 'composed/prepared early')值.保留此变量未定义使其成为可选的.

Just pass (entire 'composed/prepared earlier') value for filter (define at query) variable. Leaving this variable undefined makes it optional.

query GetUsers($filter: SomeFilterInputType) {
  users(
    first: 10, 
    filter: $filter ) {

在 [query] 变量中为 filter 传递值:

pass value for filter in [query] variables:

{
  filter: { search: 'sth'}
}

... 其中 SomeFilterInputType 是一个 [users query] arg 类型名称,它可以从 API 规范中读取,可在 graphiql/playground docs 中找到... 或服务器代码/类型定义

... where SomeFilterInputType is a [users query] arg type name, it can be read from API specs, available in graphiql/playground docs ... or server code/type defs

可以使用 QUERY VARIABLES 在 graphiql/playground 中进行测试.

It can be tested in graphiql/playground using QUERY VARIABLES.

variables 从 JavaScript 传递是一个具有相同结构的对象,很容易有条件地创建/修改.

variables passed from JavaScript is an object with the same structure, easily created/modified conditionally.

在这种情况下 SomeFilterInputType(类型名称后没有 ! 标记)意味着它(filter 变量)可以为空/未定义 - 通常可选的参数可以为空(不是必需的).如果 API/BE 规范中需要某些 arg,那么客户端也必须需要它.

In this case SomeFilterInputType (no ! mark after type name) means it (filter variable) can be nulled/undefined - usually optional args are nullable (not required). If some arg is required in API/BE specs then it must be required in client, too.

这篇关于如何有条件地在 GraphQL 查询中包含过滤参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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