简体   繁体   中英

GraphQL question about good patterns in query design

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 (eg 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?

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 (eg paperback vs hardback editions of the same title).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM