Query the User only once, via a middleware

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: performance - Apollo Server - Query the User only once, via a middleware - Stack Overflow

Thanks for your help.

@alan345 Have you seen the Putting authenticated user info on the context section of the docs? This shows you how to use the ApolloServer context option to do what you want to do.

1 Like

It also sounds like you might benefit from using something like the dataloader package?

1 Like