Search code examples
graphqlapolloapollo-client

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


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


Solution

  • 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.