2

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?

FreedomPride
  • 1,018
  • 7
  • 27
jhamm
  • 20,088
  • 33
  • 96
  • 160

2 Answers2

2

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.

stubailo
  • 5,711
  • 1
  • 22
  • 30
0

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

Haris Ghauri
  • 457
  • 1
  • 6
  • 22