diff --git a/content/graphql/resolvers-map.md b/content/graphql/resolvers-map.md index 6990434f2a..42de609879 100644 --- a/content/graphql/resolvers-map.md +++ b/content/graphql/resolvers-map.md @@ -456,6 +456,54 @@ With the above base class defined, we can now easily create specialized types th class PaginatedAuthor extends Paginated(Author) {} ``` +#### Adding state to context + +If you need to share some state, or event an instance of a class between different resolvers you can attach them to the context object and then you can access them with `@Context` decorator. To do that first we need to attach those states to the context, let's say that we need to have access to the `request`, and `response` objects in our resolver. To do so we need to configure the `context` option: + +```typescript +@Module({ + imports: [ + GraphQLModule.forRoot({ + // ... + context: ({ req, res }) => { + return { req, res }; + }, + }), + ], +}) +export class AppModule {} +``` + +And now you can define a custom type (let's call it `graphql-context.type.ts`) for your GraphQL context like this: + +```typescript +import { Response, Request } from 'express'; + +export interface GraphQLResolveContext { + req: Request; + res: Response; +} +``` + +And then in your resolver you can access it like this: + +```typescript +import { GraphQLResolveContext } from 'graphql-context.type'; + +@Resolver(() => Author) +export class AuthorsResolver { + @Query(() => Author) + author( + @Args('id', { type: () => Int }) id: number, + @Context() context: GraphQLResolveContext, + ) { + // context.req + } +} +``` + +> info **Hint** context object will be recreated for each request. This means that if you're attaching something like a [Dataloader](https://www.npmjs.com/package/dataloader) to your context object NestJS will instantiate a new instance for each request which is exactly what most people need when they are configuring Dataloader. + #### Schema first As mentioned in the [previous](/graphql/quick-start) chapter, in the schema first approach we start by manually defining schema types in SDL (read [more](https://graphql.org/learn/schema/#type-language)). Consider the following SDL type definitions. diff --git a/content/techniques/queues.md b/content/techniques/queues.md index 42d02da2bc..1e2ba40924 100644 --- a/content/techniques/queues.md +++ b/content/techniques/queues.md @@ -217,10 +217,10 @@ import { Job } from 'bullmq'; export class AudioConsumer extends WorkerHost { async process(job: Job): Promise { let progress = 0; - for (i = 0; i < 100; i++) { + for (let i = 0; i < 100; i++) { await doSomething(job.data); progress += 1; - await job.progress(progress); + await job.updateProgress(progress); } return {}; }