Accessing context values in Datasource with AS4

In As3, I was able to access the context using this.context in datasource files, but in AS4, since, datasource function is part of context. How should i able to access the context values in DS file? are there any examples ?

Yes, there are specific examples of how to do this in Migrating to Apollo Server 4 - Apollo GraphQL Docs

The easy way is to just only pass the particular parts of context that are actually needed by your data source to the data source’s constructor directly, which avoids creating a circular reference entirely. The second example shows how making your context into a class can make it easier to set up the circular reference (because you can reference this inside a constructor even though the object isn’t “done” yet).

1 Like

If you are still having any issues, we just started up an Apollo Discord for more real-time chat and livestreaming. If you come over there, feel free to ping me and we can jump on a stream to talk more about your migration.

1 Like

We would like to make the context available through out the server. So, in our case - second example suits us well. Just want to check if there are any performance concerns if we go with option as making a context into class.
Thanks for your time, support, and contribution.

I was having the same issue as mentioned in this post and have been able to get access to my datasources via context by going with the Class option.

I just noticed an issue.
I have a middleware that handles authentication and updates the context.

My datasources no longer have access to my authenticated user via the context.

Any ideas?

The docs show how to pass your context to your data sources if you’d like (the easiest way involves making your context into a class so it can refer to itself with this during its constructor even though it’s not “completed” yet).

Yeah that’s what I am doing though.

But for some reason, my datasource doesn’t my context.user variable which is only set in my middleware which runs after the context is created.

I assume its either the way I built my class context value or its because the middleware executes after?

Hard to figure out what’s going on here without seeing the code — perhaps you’re copying context.user into your data source class earlier than appropriate?