Jon_B
Jon_B

Reputation: 1079

how can I supply a a variable to a query that can be used to specify a field to sort a returned array by?

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

query getOrderedPokemon (
  $sortOrder: order_by,
)  {
  pokemon_v2_pokemon(
    limit: 20, 
    order_by: {
      name : $sortOrder
    }
  ) {
    id
    name
    height 
    weight
  }
}

With this request, I can modify the order of returned items by changing the variable $sortOrder to either 'asc' or 'desc'. What can I do if I want to sort the returned items by a different property, like height or weight? Do I have to create a new query?

If the server does not accept a variable for specifying which field to sort by, is it impossible to create a flexible query that can be sorted by variable properties?

From what I can tell, it does look like this server doesn't have any variables I can use to specify which field to sort by.

enter image description here

Thank you

Upvotes: 0

Views: 55

Answers (1)

Michel Floyd
Michel Floyd

Reputation: 20256

The pokeapi gives you quite a few options which you can see from the GraphiQL interface

To select by height in descending order for example:

query getOrderedPokemon {
  pokemon_v2_pokemon(limit: 20, order_by: {height: desc}) {
    id
    name
    height
    weight
  }
}

To make this more flexible, do:

query getOrderedPokemon($order_by: [pokemon_v2_pokemon_order_by!]) {
  pokemon_v2_pokemon(limit: 20, order_by: $order_by) {
    id
    name
    height
    weight
  }
}

Use {variables: {order_by: [{"height": "asc"}]}} to order by height or {variables: {order_by: [{weight: "asc"}]}} to order by weight.

Upvotes: 1

Related Questions