When the frontend make an API request to the graphQL server (Apollo Server), I realize that I call very often the same function: utils.getUser()
too many times. This function is a SQL query that hits the database.
This function is called many times within the same request:
- A first time in the directives, to check the role of the user making the request.
- In the resolvers. (to write a log for example)
- In a child resolver. (to return a specific field based on the role of the user for example)
Ideally we should call utils.getUser()
in a middleware and update the context ctx
, as the context is forwarded to all resolvers.
Instead of :
createReview: async (parent, args, ctx, info) => {
const user = await utils.getUser(ctx) // Request SQL to get the User data
...
}
having
createReview: async (parent, args, ctx, info) => {
const user = ctx.user
...
}
Question related to: https://stackoverflow.com/questions/68551981/apollo-server-query-the-user-only-once-via-a-middleware
Thanks for your help.