Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return a single or multiple results from the same graphQL query?

Tags:

graphql

I have set up a GraphQL endpoint that returns me a client

query {
    client(id:1) {
      clientId
    }
}

and another that returns a list of clients

query {
    clients {
      clientId
    }
}

I have 2 backing db queries for these 2 graphql queries, but is there a way to have a single query for both? Or what is the graphql way of handling this?

like image 841
jhamm Avatar asked Oct 17 '25 22:10

jhamm


2 Answers

The GraphQL way of handling this is exactly how you have done it. You usually need separate fields in your schema to handle retrieving one item vs multiple, just like you would have separate endpoints for these in a REST API.

like image 136
stubailo Avatar answered Oct 19 '25 12:10

stubailo


You can have a single end point that returns a GraphQLList Type. This list can contain either one object or however many.

In your case, that single end point will be clients. You just have to use your backend to see if the consumer of your GraphQL API has supplied any arguments i.e. clientId. If the clientId has been supplied, filter your clientRepo by that supplied clientId. Otherwise return the whole list (repo) of clients.

clients: {
  type: new GraphQLList(clientType), <--- Note this is a GraphQLList type
  args: {
    id: {
      type: GraphQLInt
    },
  },
  resolve: (parent, args) => {
    if (args.id) {
      return clientRepo.find(args.id);
    }
    return clientRepo.findAll();
  }
}

You might want to visit the following links:

https://jaketrent.com/post/return-array-graphql/

https://stackoverflow.com/a/52773152/4195803

like image 44
Haris Ghauri Avatar answered Oct 19 '25 12:10

Haris Ghauri