如何根据传递给它的变量修改 GraphQL 查询?

huangapple go评论67阅读模式
英文:

How can I modify a graphQL query based off of the variable passed to it?

问题

我已经构建了此查询以从Pokeapi的GraphQL服务器https://beta.pokeapi.co/graphql/console/请求数据。

query getPokemon (
  $typesList: [Int!],
)  {
  pokemon_v2_pokemon(
    where: { 
      pokemon_v2_pokemontypes: { type_id: { _in: $typesList } }
    }
  ) {
    id
    name
    pokemon_v2_pokemontypes {
      type_id
      pokemon_v2_type {
        name
      }
    }
  }
}

$typesList列表为空时,你可以修改查询以返回所有结果。在GraphQL中,你可以使用条件来实现这一点。你可以检查$typesList是否为空,如果为空,则不应用筛选条件,否则应用筛选条件。以下是修改后的查询:

query getPokemon (
  $typesList: [Int!],
)  {
  pokemon_v2_pokemon(
    where: { 
      pokemon_v2_pokemontypes: { type_id: { _in: $typesList } }
    }
  ) {
    id
    name
    pokemon_v2_pokemontypes @skip(if: $typesList_empty) {
      type_id
      pokemon_v2_type {
        name
      }
    }
  }
}

在此查询中,我们使用了@skip指令,该指令根据条件跳过字段的选择。如果$typesList为空(即条件为真),则不选择pokemon_v2_pokemontypes字段,从而返回所有结果。如果$typesList不为空,那么筛选条件将被应用。

这是一种在GraphQL中实现条件查询的方法。希望这对你有所帮助。

英文:

I have built this query to request data from the Pokeapi graphQL server here
https://beta.pokeapi.co/graphql/console/

query getPokemon (
  $typesList: [Int!],
)  {
  pokemon_v2_pokemon(
    where: { 
      pokemon_v2_pokemontypes: { type_id: { _in: $typesList } }
    }
  ) {
    id
    name
    pokemon_v2_pokemontypes {
      type_id
      pokemon_v2_type {
        name
      }
    }
  }
}

How can I modify the query to return all results when the $typesList list is empty? I would like the query to return a filtered results list when $typesList has a list of ids, but it should return all values when the $typesList list is empty.

Is this something that is possible in graphQL?

Thank you

答案1

得分: 0

如果你控制服务器,你可以编写解析器以按照你希望的方式运行,但由于你没有控制权,你唯一的选择是将查询的使用包装在某种方式,以将默认的 typesList 变量设置为所有可能的类型。

英文:

If you controlled the server you could write the resolver to function in the manner you're looking for but since you don't your only option is to wrap your use of the query with something that sets the default typesList variable to all possible types.

huangapple
  • 本文由 发表于 2023年2月18日 08:54:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75490482.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定