英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论