Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Global context (Async Local Storage) #5453

Closed
A-Shleifman opened this issue Jul 9, 2021 · 3 comments
Closed

Global context (Async Local Storage) #5453

A-Shleifman opened this issue Jul 9, 2021 · 3 comments

Comments

@A-Shleifman
Copy link

A-Shleifman commented Jul 9, 2021

The context Apollo Server exposes through resolvers is very convenient when using it within the same function, however, when more layers are added, passing ctx all around becomes messy.

Let's say we have a tenantId and tenantName that we extract from headers on every request. We need to pass them on to internal APIs down the line, but we have the following structure:

resolver.ts => service.ts => internalApiRequests.ts

Can we pass ctx down to the function that consumes it? - absolutely, is it clean? - no.

I tried writing an express middleware that would wrap next() in Node's AsyncLocalStorage, but it doesn't work. This was brought up previously regarding a library that was trying to achieve the same goal.

Then I wrote a wrapper withCtx that wraps around resolvers and the context becomes available in all downstream functions, but I have to wrap every resolver manually.

Is there a way to make express middleware work? Alternatively, is there some kind of apollo middleware that would allow wrapping the rest of the request in an ALS?

@A-Shleifman
Copy link
Author

Using localStorage.enterWith instead of localStorage.run does the trick:

app.use((req, res, next) => {
  // localStorage.run(context, next)) <-- this doesn't work
  localStorage.enterWith(context);

  next();
});

Full solution: https://codesandbox.io/s/pensive-beaver-7w88e

@ghost
Copy link

ghost commented Oct 4, 2022

Both localStorage.enterWith and localStorage.run work for me in apollo-server-express@2.26.0.

Same code from https://codesandbox.io/s/pensive-beaver-7w88e doesnt work in 3.0.0

Edit:
Doesn't work in Node 18

@A-Shleifman
Copy link
Author

Updated and slightly simplified example with Apollo 3 and Node 16

Open a new terminal in codesandbox and run yarn start

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Apr 20, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant