I am working with two unique GraphQL types:
type Author {
id: String!
name: String!
}
type Book {
id: String!
author: Author!
name: String!
}
Within my database structure, there exists a foreign key inside the books
table:
table authors
(pseudo code)
`id` INTEGER UNSIGNED
`name` STRING
table books
(pseudo code)
`id` INTEGER UNSIGNED
`author_id` INTEGER UNSIGNED REFERENCE `authors.id`
`name` STRING
When resolving a GraphQL query like the following:
query allTheBooks {
id
name
author {
id
}
}
I want to avoid executing an additional SQL query beyond the one retrieving the list of books, as the necessary data is already present in the books.author_id
field.
To achieve this optimization, I replaced the existing JavaScript code:
Book: {
async author(book, args, context, info) {
// this code trigger a database SELECT query that fetch all the fields of the author row associated with the book
return book.author().get();
}
}
with:
Book: {
async author(book, args, context, info) {
return {
id: book.author_id,
}
}
}
This solution proved to be effective, resulting in only one SQL query being executed where previously there were multiple queries.
However, I am seeking a way to retrieve the other fields without issuing individual queries per field.
I theorize that it may be achievable by returning a single promise for all fields, which would then resolve with the complete contents of the author
row. Yet, I am curious if there exists a more streamlined approach...
I appreciate your insights on this matter!