Home > Blockchain >  GraphQL question about good patterns in query design
GraphQL question about good patterns in query design

Time:12-12

I'm pretty new in Graphql and API development in general.

There are many tutorials around but sometimes I have doubts about some implementation patterns. In particular, I was wondering about best practices for writing GraphQL schemas.

In almost all tutorials (as is the case with REST APIs) when it comes to writing a query to retrieve a list of entities it is usually presented as follows:

query{
    Books{
       id,
       title,
       something
}}

Almost always another query is then presented for the recovery of a single object of that entity, for example:

query{
    Book(id:id){
       id,
       title,
       something
}}

here comes my first implementation doubt. When I go to write the function that interfaces with the database for data retrieval, the code is practically the same for both resolvers. Only that in the second case I will add a where clause (e.g. where bookID = id)

At this point I was wondering, why can't I use a single query and add the various filters as arguments?

query{
    Books(filters:{id:id, title:title, ...}){
       id,
       title,
       something
}}

What's the point of adding a different query for each filter?

  • Books
  • BookById
  • BookbyTitle
  • ...

Is it just a matter of better organization of the entry points or am I missing something else?

While for REST API this makes sense to me, with GraphQL I fail to see the benefit since the overfetching is not a problem.

Could someone be so kind as to enlighten me?

CodePudding user response:

You're right that this is a subjective decision and you could go either way. You should expect opinionated answers here.

When you define a query in your typeDefs, you also specify what you expect to get back. Ex:

query {
  getBook (id: ID!): Book
  getBooks: [Book!]!
}

In the first query you know that the return object is a single book. In the second you're going to get an array of books.

If you build queries that can either return one or more books that's fine - you can expect an array which may only have one book in it.

It's when you expect a single book but get multiple books back that you may face problems in your front end. If you query books by ID you expect a single book but if you query books by title you might get 0, 1, or N books back if there happen to be multiple books with the same title (e.g. paperback vs hardback editions of the same title).

  • Related