typegraphql-nestjs icon indicating copy to clipboard operation
typegraphql-nestjs copied to clipboard

feat: allow injection of context

Open ahilke opened this issue 9 months ago • 1 comments

Fixes https://github.com/MichalLytek/typegraphql-nestjs/issues/54 (and I believe https://github.com/MichalLytek/typegraphql-nestjs/issues/22).

Registers the context object within Nest's dependency-injection sub-tree, so that it can be injected with @Inject(CONTEXT) from @nestjs/graphql (@Inject(REQUEST) from @nestjs/core also works), following https://docs.nestjs.com/fundamentals/module-ref#registering-request-provider. To quote:

Manually generated context identifiers (with ContextIdFactory.create()) represent DI sub-trees in which REQUEST provider is undefined as they are not instantiated and managed by the Nest dependency injection system.

To register a custom REQUEST object for a manually created DI sub-tree, use the ModuleRef#registerRequestByContextId() method

This allows accessing the context object from anywhere that allows injection, not just in resolvers, for example to provide request-specific logs. Since @Inject(REQUEST) also works, this makes it possible to write functionality that works for both GraphQL and REST endpoints.

I confirmed the behaviour using my reproduction project: https://github.com/ahilke/typegraphql-nestjs-inject-context/

I believe this adds considerable value to the library, as otherwise one has to work around GraphQL specifics to access the context/request.

ahilke avatar May 07 '24 20:05 ahilke