Add to Apollo Server context after document is parsed, but before root query

Hi there!

I am trying to figure out how I can add something to the Apollo Server context (one of the 4 positional arguments) AFTER the document has been parsed but before any resolvers get going.

The use case is that we would like to add DataLoaders (request-specific caching mechanisms) to the context for queries, but not mutations. So we need to be able to identify whether the request is a query or mutation and then do something to context, before individual fields are resolved.

What I think might solve this problem:

  • Having access to context and the Document at the same time, somewhere early in execution.
  • Being able to do a resolver for Query and Mutation namespaces / roots. Since a resolver has access to positional arguments, I think that would allow me to modify context accordingly.

Things I already tried:

1. Add to context

Add to context via the context argument when starting the server. Similar to how the documentation recommends adding authentication:

Unfortunately this happens too early in the request lifecycle. At this point, we only have Next.js req and res and nothing GraphQL- specific. This makes it very hard to identify whether a particular query is a query or mutation (without doing something sketchy, like looking for the word “mutation” in the request body).

2. Use plugin and lifecycle hooks

Using lifecycle hooks in a plugin like executionDidStart and willResolveField might in theory give us access to context. But only willResolveField has access to positional arguments like context, but it has to be set up via executionDidStart. This ends up running something that should be only run once, a ton of times (once for every resolver) and is really spaghetti.

Any help much appreciated! Thanks.