Extend the WunderGraph server context
Using the context factory
When calling handler functions, be it a TypeScript operation or a hook, WunderGraph provides a context object which allows you to read information like the currently logged in user or the client request. However, in some circumstances you might also want you store additional data in that context.
To solve this problem, WunderGraph provides support for instantiating a custom context on every handler invocation. To use it, declare a function that returns your context type and pass it to createWunderGraphServer()
:
This will create a per-request context for every request, pass it to every handler and finally call context.release
, giving it a chance to free any pending resources.
Additionally, this context can also be used from TypeScript functions:
As well as from webhooks:
And embedded GraphQL servers:
Storing global data
Besides the per-request context, WunderGraph suports a global context too. This context gets instantiated once when the server starts and can be used when instantiating the per-request contexts:
This pattern can be used with popular dependency injection frameworks like awilix .