nestjs-boost 0.0.0-stage → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +68 -0
- package/LICENSE +21 -0
- package/NOTICE.md +6 -0
- package/README.md +168 -2
- package/bin/nestjs-boost.mjs +148 -0
- package/guidelines/core.md +64 -0
- package/lib/agents.mjs +137 -0
- package/lib/installer.mjs +450 -0
- package/lib/prompt.mjs +131 -0
- package/lib/setup.mjs +60 -0
- package/manifest.json +676 -0
- package/package.json +67 -6
- package/scripts/postinstall.mjs +49 -0
- package/skills/nestjs-ai/SKILL.md +145 -0
- package/skills/nestjs-ai/references/ai-reference.md +143 -0
- package/skills/nestjs-architecture/SKILL.md +83 -0
- package/skills/nestjs-architecture/references/dynamic-modules.md +92 -0
- package/skills/nestjs-architecture/references/scopes-lifecycle.md +98 -0
- package/skills/nestjs-architecture/references/troubleshooting.md +77 -0
- package/skills/nestjs-authentication/SKILL.md +115 -0
- package/skills/nestjs-authentication/references/flows.md +180 -0
- package/skills/nestjs-authorization/SKILL.md +104 -0
- package/skills/nestjs-caching/SKILL.md +109 -0
- package/skills/nestjs-cli-tooling/SKILL.md +94 -0
- package/skills/nestjs-cli-tooling/references/nest-cli-json.md +91 -0
- package/skills/nestjs-configuration/SKILL.md +109 -0
- package/skills/nestjs-cqrs/SKILL.md +124 -0
- package/skills/nestjs-database-drizzle/SKILL.md +117 -0
- package/skills/nestjs-database-mikro-orm/SKILL.md +109 -0
- package/skills/nestjs-database-mongoose/SKILL.md +124 -0
- package/skills/nestjs-database-prisma/SKILL.md +126 -0
- package/skills/nestjs-database-sequelize/SKILL.md +88 -0
- package/skills/nestjs-database-typeorm/SKILL.md +110 -0
- package/skills/nestjs-deployment/SKILL.md +133 -0
- package/skills/nestjs-deployment/references/serverless-and-systemd.md +133 -0
- package/skills/nestjs-events/SKILL.md +78 -0
- package/skills/nestjs-file-storage/SKILL.md +111 -0
- package/skills/nestjs-file-storage/references/storage-reference.md +82 -0
- package/skills/nestjs-graphql/SKILL.md +119 -0
- package/skills/nestjs-graphql/references/federation.md +110 -0
- package/skills/nestjs-graphql/references/schema-features.md +133 -0
- package/skills/nestjs-health-checks/SKILL.md +114 -0
- package/skills/nestjs-http-client/SKILL.md +118 -0
- package/skills/nestjs-http-client/references/http-client-reference.md +116 -0
- package/skills/nestjs-http-platform/SKILL.md +104 -0
- package/skills/nestjs-http-platform/references/adapters.md +88 -0
- package/skills/nestjs-http-web-features/SKILL.md +113 -0
- package/skills/nestjs-http-web-features/references/uploads-streaming.md +108 -0
- package/skills/nestjs-i18n/SKILL.md +113 -0
- package/skills/nestjs-idempotency/SKILL.md +112 -0
- package/skills/nestjs-locks/SKILL.md +108 -0
- package/skills/nestjs-logging/SKILL.md +123 -0
- package/skills/nestjs-mail/SKILL.md +125 -0
- package/skills/nestjs-mail/references/mail-reference.md +90 -0
- package/skills/nestjs-mcp-server/SKILL.md +152 -0
- package/skills/nestjs-mcp-server/references/mcp-reference.md +146 -0
- package/skills/nestjs-microservices/SKILL.md +108 -0
- package/skills/nestjs-microservices/references/transports.md +117 -0
- package/skills/nestjs-observability/SKILL.md +108 -0
- package/skills/nestjs-observability/references/apm-and-otel.md +106 -0
- package/skills/nestjs-openapi/SKILL.md +90 -0
- package/skills/nestjs-openapi/references/swagger-reference.md +180 -0
- package/skills/nestjs-outbox/SKILL.md +119 -0
- package/skills/nestjs-outbox/references/outbox-reference.md +74 -0
- package/skills/nestjs-passport-auth/SKILL.md +125 -0
- package/skills/nestjs-queues/SKILL.md +118 -0
- package/skills/nestjs-queues/references/bull-legacy.md +75 -0
- package/skills/nestjs-request-pipeline/SKILL.md +146 -0
- package/skills/nestjs-request-pipeline/references/filters-interceptors.md +114 -0
- package/skills/nestjs-request-pipeline/references/pipes-decorators.md +80 -0
- package/skills/nestjs-resilience/SKILL.md +116 -0
- package/skills/nestjs-resilience/references/resilience-reference.md +74 -0
- package/skills/nestjs-scheduling/SKILL.md +100 -0
- package/skills/nestjs-security-hardening/SKILL.md +99 -0
- package/skills/nestjs-security-hardening/references/throttler-advanced.md +78 -0
- package/skills/nestjs-standalone-apps/SKILL.md +78 -0
- package/skills/nestjs-testing/SKILL.md +118 -0
- package/skills/nestjs-testing/references/advanced-testing.md +62 -0
- package/skills/nestjs-upgrading/SKILL.md +82 -0
- package/skills/nestjs-upgrading/references/esm-switch.md +114 -0
- package/skills/nestjs-validation-serialization/SKILL.md +124 -0
- package/skills/nestjs-validation-serialization/references/validation-options.md +84 -0
- package/skills/nestjs-webhooks/SKILL.md +116 -0
- package/skills/nestjs-webhooks/references/webhooks-reference.md +132 -0
- package/skills/nestjs-websockets/SKILL.md +108 -0
- package/skills/nestjs-workflows/SKILL.md +123 -0
- package/skills/nestjs-workflows/references/workflows-reference.md +85 -0
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: nestjs-queues
|
|
3
|
+
description: Runs background jobs in NestJS 12 with Redis-backed queues via @nestjs/bullmq (and legacy @nestjs/bull) — BullModule.forRoot/forRootAsync and registerQueue, named Redis configurations, producers with @InjectQueue and Queue.add job options (attempts, backoff, delay, priority, jobId dedupe, removeOnComplete), repeatable jobs with upsertJobScheduler, consumers extending WorkerHost with process() and a switch on job.name, request-scoped consumers with JOB_REF, @OnWorkerEvent and @QueueEventsListener/@OnQueueEvent listeners, flows, sandboxed processors, pause/resume, manual registration, and observing queues. Use when work should happen outside the request (emails, transcoding, imports, webhooks to slow APIs), needs retries with backoff, must be spread across workers, or when jobs don't process, run twice or pile up. Not for in-process events (nestjs-events), transactional outbox delivery (nestjs-outbox), multi-step durable processes (nestjs-workflows) or cron schedules alone (nestjs-scheduling).
|
|
4
|
+
compatibility: NestJS 12.x; @nestjs/bullmq + bullmq (recommended) or @nestjs/bull + bull (maintenance mode); Redis
|
|
5
|
+
metadata:
|
|
6
|
+
version: "0.1.0"
|
|
7
|
+
nestjs-major: "12"
|
|
8
|
+
docs-crawled: "2026-11-05"
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
# NestJS queues (BullMQ)
|
|
12
|
+
|
|
13
|
+
Use `@nestjs/bullmq` for new code; `@nestjs/bull` is in maintenance mode. If the project already uses Bull, read `references/bull-legacy.md` before editing — the APIs differ.
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm i @nestjs/bullmq bullmq
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Setup
|
|
20
|
+
|
|
21
|
+
```typescript
|
|
22
|
+
// app.module.ts
|
|
23
|
+
BullModule.forRootAsync({
|
|
24
|
+
inject: [ConfigService],
|
|
25
|
+
useFactory: (config: ConfigService) => ({
|
|
26
|
+
connection: { url: config.getOrThrow<string>('REDIS_URL') },
|
|
27
|
+
defaultJobOptions: { attempts: 3, backoff: { type: 'exponential', delay: 1000 }, removeOnComplete: 1000, removeOnFail: 5000 },
|
|
28
|
+
}),
|
|
29
|
+
}),
|
|
30
|
+
|
|
31
|
+
// media/media.module.ts
|
|
32
|
+
@Module({
|
|
33
|
+
imports: [BullModule.registerQueue({ name: 'audio' })],
|
|
34
|
+
providers: [AudioService, AudioConsumer, AudioEventsListener], // consumers and listeners MUST be providers
|
|
35
|
+
})
|
|
36
|
+
export class MediaModule {}
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
- Shared options: `connection`, `prefix` (`bull`), `defaultJobOptions` (not applied to `FlowProducer` jobs), `settings`, `extraOptions`.
|
|
40
|
+
- Per queue overrides in `registerQueue({ name, connection, … })`; async: `registerQueueAsync({ name, useFactory })` (name outside the factory).
|
|
41
|
+
- Another Redis: `BullModule.forRoot('alt', { connection })` + `registerQueue({ name: 'video', configKey: 'alt' })`.
|
|
42
|
+
|
|
43
|
+
## Producer
|
|
44
|
+
|
|
45
|
+
```typescript
|
|
46
|
+
@Injectable()
|
|
47
|
+
export class AudioService {
|
|
48
|
+
constructor(@InjectQueue('audio') private readonly audioQueue: Queue) {}
|
|
49
|
+
enqueue(fileId: string) {
|
|
50
|
+
return this.audioQueue.add('transcode', { fileId }, { jobId: `transcode:${fileId}`, priority: 2, delay: 3000 });
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
- Job data must be JSON-serializable: pass ids, not entities.
|
|
56
|
+
- `jobId` dedupes (an existing id isn't added again). Other options: `attempts` (default 1), `backoff`, `lifo`, `removeOnComplete`, `removeOnFail`, `stackTraceLimit`.
|
|
57
|
+
- Repeating jobs: `queue.upsertJobScheduler(id, { pattern: '0 2 * * *' }, { name, data })` — BullMQ no longer accepts `repeat` in `add()`.
|
|
58
|
+
- Enqueue **after** the DB transaction commits, or use the outbox (nestjs-outbox) when the job must exist iff the transaction commits.
|
|
59
|
+
|
|
60
|
+
## Consumer
|
|
61
|
+
|
|
62
|
+
```typescript
|
|
63
|
+
@Processor('audio', { concurrency: 5 })
|
|
64
|
+
export class AudioConsumer extends WorkerHost {
|
|
65
|
+
private readonly logger = new Logger(AudioConsumer.name);
|
|
66
|
+
|
|
67
|
+
async process(job: Job<{ fileId: string }>): Promise<unknown> {
|
|
68
|
+
switch (job.name) { // BullMQ has no @Process('name')
|
|
69
|
+
case 'transcode':
|
|
70
|
+
await this.transcoder.run(job.data.fileId, (p) => job.updateProgress(p));
|
|
71
|
+
return { done: true };
|
|
72
|
+
default:
|
|
73
|
+
throw new Error(`Unknown job ${job.name}`);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
@OnWorkerEvent('failed')
|
|
78
|
+
onFailed(job: Job, err: Error) { this.logger.error(`Job ${job.id} failed (attempt ${job.attemptsMade})`, err.stack); }
|
|
79
|
+
}
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
- Make handlers **idempotent**: jobs are retried and can run more than once after a stalled worker.
|
|
83
|
+
- Throw to fail (retried per `attempts`/`backoff`); return a value to store as the result.
|
|
84
|
+
- Queue-level listeners: `@QueueEventsListener('audio') class X extends QueueEventsHost { @OnQueueEvent('completed') … }` (receive `{ jobId, … }`, not jobs).
|
|
85
|
+
- Request-scoped: `@Processor({ name: 'audio', scope: Scope.REQUEST })` + `@Inject(JOB_REF) job`.
|
|
86
|
+
- MikroORM users: decorate `process()` with `@CreateRequestContext()` (below other decorators).
|
|
87
|
+
- Pause/resume: `queue.pause()` / `queue.resume()`; counts and cleanup on the `Queue` API.
|
|
88
|
+
- Flows (parent/child jobs): `BullModule.registerFlowProducer({ name })` + `@InjectFlowProducer(name)`.
|
|
89
|
+
|
|
90
|
+
## Separate processes and workers
|
|
91
|
+
|
|
92
|
+
- Sandboxed processors: `registerQueue({ name, processors: [join(import.meta.dirname, 'processor.js')] })` — runs in a fork, **no DI**.
|
|
93
|
+
- Dedicated worker deployment: a standalone app (nestjs-standalone-apps) importing the consumer modules; API pods only produce.
|
|
94
|
+
- `extraOptions: { manualRegistration: true }` + `BullRegistrar.register()` to start workers conditionally (e.g. only when `ROLE=worker`).
|
|
95
|
+
|
|
96
|
+
## Observability
|
|
97
|
+
|
|
98
|
+
Watch wait time vs run time, attempts, failures and "job hasn't run" silence. `@nestjs/observe` instruments `@Processor()` classes automatically (nestjs-observability).
|
|
99
|
+
|
|
100
|
+
## Testing
|
|
101
|
+
|
|
102
|
+
- Producer: `{ provide: getQueueToken('audio'), useValue: { add: vi.fn() } }`.
|
|
103
|
+
- Consumer: instantiate and call `process({ name: 'transcode', data, updateProgress: vi.fn() } as any)`.
|
|
104
|
+
- Integration: real Redis (Testcontainers) and wait for `completed` via `QueueEvents`.
|
|
105
|
+
|
|
106
|
+
## Workflow
|
|
107
|
+
|
|
108
|
+
- [ ] 1. Install; `forRootAsync` with Redis from config and sensible `defaultJobOptions`.
|
|
109
|
+
- [ ] 2. `registerQueue` in the feature module; producer service with `@InjectQueue`.
|
|
110
|
+
- [ ] 3. Consumer extending `WorkerHost` with a `switch` on `job.name`; listeners; all registered as providers.
|
|
111
|
+
- [ ] 4. Idempotency, retries, removal policies; worker placement (in-process vs worker deployment).
|
|
112
|
+
- [ ] 5. Tests. Build, lint, run tests, start the app with Redis.
|
|
113
|
+
|
|
114
|
+
## Reference files
|
|
115
|
+
|
|
116
|
+
- `references/bull-legacy.md`: `@nestjs/bull` API (named `@Process()`, `@OnQueue*` events, `Queue` from bull, options) and a migration map to BullMQ. Read when the project uses `@nestjs/bull`.
|
|
117
|
+
|
|
118
|
+
Sources: [Queues](https://docs.nestjs.com/application/queues)
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# @nestjs/bull (legacy Bull)
|
|
2
|
+
|
|
3
|
+
Bull is in maintenance mode (bug fixes only). Keep using it in projects that already do; plan migrations to BullMQ deliberately (job data in Redis is not shared between the two).
|
|
4
|
+
|
|
5
|
+
## Contents
|
|
6
|
+
- Setup
|
|
7
|
+
- Producers and job options
|
|
8
|
+
- Consumers
|
|
9
|
+
- Events
|
|
10
|
+
- Migration map to BullMQ
|
|
11
|
+
|
|
12
|
+
## Setup
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npm i @nestjs/bull bull
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
```typescript
|
|
19
|
+
BullModule.forRoot({ redis: { host: 'localhost', port: 6379 } }); // also: limiter, prefix, defaultJobOptions, settings
|
|
20
|
+
BullModule.registerQueue({ name: 'audio' }); // per-queue `redis` override; `configKey` for named configs
|
|
21
|
+
BullModule.forRoot('alternative-config', { redis: { port: 6381 } });
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Async: `forRootAsync({ useFactory, inject })` (`useClass` implements `SharedBullConfigurationFactory`), `registerQueueAsync({ name, useFactory })`.
|
|
25
|
+
|
|
26
|
+
## Producers and job options
|
|
27
|
+
|
|
28
|
+
```typescript
|
|
29
|
+
constructor(@InjectQueue('audio') private readonly audioQueue: Queue) {} // Queue from 'bull'
|
|
30
|
+
await this.audioQueue.add({ foo: 'bar' }); // unnamed
|
|
31
|
+
await this.audioQueue.add('transcode', { foo: 'bar' }, { delay: 3000 }); // named: needs a @Process('transcode') handler
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Options: `priority` (1 = highest), `delay`, `attempts`, `repeat` (cron `RepeatOpts`), `backoff`, `lifo`, `timeout`, `jobId`, `removeOnComplete`, `removeOnFail`, `stackTraceLimit`.
|
|
35
|
+
|
|
36
|
+
With named jobs, every name added to a queue needs a processor, or the queue reports a missing processor.
|
|
37
|
+
|
|
38
|
+
## Consumers
|
|
39
|
+
|
|
40
|
+
```typescript
|
|
41
|
+
@Processor('audio')
|
|
42
|
+
export class AudioConsumer {
|
|
43
|
+
@Process('transcode')
|
|
44
|
+
async transcode(job: Job<unknown>) {
|
|
45
|
+
await job.progress(50);
|
|
46
|
+
return {};
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
- Consumers must be providers. Request-scoped: `@Processor({ name: 'audio', scope: Scope.REQUEST })` + `@Inject(JOB_REF)`.
|
|
52
|
+
- Several consumers on one queue: `@Process({ concurrency: 1 })` doesn't take effect; minimum concurrency = number of consumers.
|
|
53
|
+
- Sandboxed: `registerQueue({ name: 'audio', processors: [join(import.meta.dirname, 'processor.js')] })` (no DI).
|
|
54
|
+
|
|
55
|
+
## Events
|
|
56
|
+
|
|
57
|
+
Declared inside the `@Processor()` class:
|
|
58
|
+
- Local: `@OnQueueError`, `@OnQueueWaiting`, `@OnQueueActive`, `@OnQueueStalled`, `@OnQueueProgress`, `@OnQueueCompleted`, `@OnQueueFailed`, `@OnQueuePaused`, `@OnQueueResumed`, `@OnQueueCleaned`, `@OnQueueDrained`, `@OnQueueRemoved`.
|
|
59
|
+
- Global (events from other processes): the same with `@OnGlobalQueue…()`; handlers get a `jobId` instead of a `job` (fetch with `queue.getJob(jobId)`).
|
|
60
|
+
- Generic: `@OnQueueEvent(BullQueueEvents.COMPLETED)` / `BullQueueGlobalEvents`.
|
|
61
|
+
|
|
62
|
+
## Migration map to BullMQ
|
|
63
|
+
|
|
64
|
+
| Bull (`@nestjs/bull`) | BullMQ (`@nestjs/bullmq`) |
|
|
65
|
+
| --- | --- |
|
|
66
|
+
| `redis: {...}` | `connection: {...}` |
|
|
67
|
+
| `queue.add(data)` / `add(name, data)` | `queue.add(name, data)` (name required) |
|
|
68
|
+
| `@Process('name')` methods | `class X extends WorkerHost { process(job) { switch (job.name) … } }` |
|
|
69
|
+
| `job.progress(n)` | `job.updateProgress(n)` |
|
|
70
|
+
| `repeat` option | `queue.upsertJobScheduler()` |
|
|
71
|
+
| `timeout` option | handle timeouts in the processor (e.g. AbortSignal) |
|
|
72
|
+
| `@OnQueueActive()` etc. in the processor | `@OnWorkerEvent('active')` in the processor; `@QueueEventsListener` + `@OnQueueEvent` for queue-wide events |
|
|
73
|
+
| `priority` 1 = highest | `priority` 0 = none, then lower = higher |
|
|
74
|
+
|
|
75
|
+
Drain the Bull queues (or run both workers side by side) before switching producers.
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: nestjs-request-pipeline
|
|
3
|
+
description: Builds and debugs the NestJS 12 HTTP request pipeline — controllers and routing, middleware, guards, interceptors, pipes, exception filters and custom decorators — including their execution order, global vs controller vs route binding, metadata decorators read with Reflector, machine-readable errorCode responses, and route conflict detection. Use when adding cross-cutting behaviour (auth checks, roles, public routes, response wrapping, timing, error formatting), when a guard/pipe/interceptor/filter isn't running or runs in the wrong order, when a route like /users/me is matched by /users/:id, or when designing controller routes. Not for validation DTOs/schemas (nestjs-validation-serialization), authentication strategies (nestjs-authentication, nestjs-passport-auth) or GraphQL/WebSocket/microservice enhancers.
|
|
4
|
+
compatibility: NestJS 12.x
|
|
5
|
+
metadata:
|
|
6
|
+
version: "0.1.0"
|
|
7
|
+
nestjs-major: "12"
|
|
8
|
+
docs-crawled: "2026-11-04"
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
# NestJS request pipeline
|
|
12
|
+
|
|
13
|
+
## Which component for which job
|
|
14
|
+
|
|
15
|
+
| Job | Component | Why |
|
|
16
|
+
| --- | --- | --- |
|
|
17
|
+
| Raw request/response work before routing (logging, headers, body parsing) | Middleware | Runs before a handler is chosen; no `ExecutionContext` |
|
|
18
|
+
| Allow or deny a request (auth, roles, API keys) | Guard (`CanActivate`) | Knows the target handler and its metadata; runs before interceptors and pipes |
|
|
19
|
+
| Transform or validate one argument | Pipe (`PipeTransform`) | Runs per parameter, right before the handler |
|
|
20
|
+
| Wrap the handler (map the response, timing, caching, timeouts) | Interceptor (`NestInterceptor`) | Sees before *and* after the handler, as an Observable |
|
|
21
|
+
| Shape error responses | Exception filter (`@Catch`) | Runs only for uncaught exceptions |
|
|
22
|
+
| Pull a value into a handler parameter (`@CurrentUser()`) | `createParamDecorator` | Reads from `ExecutionContext` |
|
|
23
|
+
| Attach per-route metadata (`@Public()`, `@Roles()`) | `Reflector.createDecorator<T>()`, or `SetMetadata` for argument-less flags | Read in guards/interceptors with `Reflector` |
|
|
24
|
+
|
|
25
|
+
Scaffold with the CLI: `npx nest g guard auth/api-key`, `nest g interceptor`, `nest g filter`, `nest g pipe`, `nest g decorator`. In v12, `nest g decorator` generates the `Reflector.createDecorator()` form.
|
|
26
|
+
|
|
27
|
+
## Execution order
|
|
28
|
+
|
|
29
|
+
1. Middleware: `app.use()`-bound first, then module-bound, in binding order.
|
|
30
|
+
2. Guards: global → controller → route.
|
|
31
|
+
3. Interceptors, before the handler: global → controller → route.
|
|
32
|
+
4. Pipes: global → controller → route → parameter. With several parameters, the **last parameter is processed first**.
|
|
33
|
+
5. The handler.
|
|
34
|
+
6. Interceptors, after the handler: route → controller → global.
|
|
35
|
+
7. Exception filters: **route → controller → global**. The first filter that catches the exception handles it; it is not passed on.
|
|
36
|
+
|
|
37
|
+
Two exceptions to this order:
|
|
38
|
+
- Exceptions thrown in middleware reach **global filters only**.
|
|
39
|
+
- Exceptions you catch yourself never reach a filter.
|
|
40
|
+
|
|
41
|
+
([Request lifecycle](https://docs.nestjs.com/faq/request-lifecycle))
|
|
42
|
+
|
|
43
|
+
## Binding globally: use APP_* providers
|
|
44
|
+
|
|
45
|
+
Default to registering global enhancers as providers in a module. This gives them DI, and they are active wherever the module is loaded, including in tests built from `AppModule`:
|
|
46
|
+
|
|
47
|
+
```typescript
|
|
48
|
+
import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
|
|
49
|
+
|
|
50
|
+
@Module({
|
|
51
|
+
providers: [
|
|
52
|
+
{ provide: APP_GUARD, useExisting: ApiKeyGuard }, ApiKeyGuard, // useExisting lets tests overrideProvider(ApiKeyGuard)
|
|
53
|
+
{ provide: APP_FILTER, useClass: AllExceptionsFilter },
|
|
54
|
+
],
|
|
55
|
+
})
|
|
56
|
+
export class AppModule {}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
`app.useGlobalGuards(new X())` in `main.ts` cannot inject dependencies. It does not apply to connected microservices in hybrid apps (guards, pipes), and for filters it does not apply to gateways or hybrid apps. Multiple global guards run in registration order.
|
|
60
|
+
|
|
61
|
+
## Pattern: guard with public routes (metadata + Reflector)
|
|
62
|
+
|
|
63
|
+
```typescript
|
|
64
|
+
// auth/public.decorator.ts — a flag with no arguments: SetMetadata + exported key
|
|
65
|
+
import { SetMetadata } from '@nestjs/common';
|
|
66
|
+
export const IS_PUBLIC_KEY = 'isPublic';
|
|
67
|
+
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
|
|
68
|
+
|
|
69
|
+
// auth/api-key.guard.ts
|
|
70
|
+
@Injectable()
|
|
71
|
+
export class ApiKeyGuard implements CanActivate {
|
|
72
|
+
constructor(private readonly reflector: Reflector, private readonly config: ConfigService) {}
|
|
73
|
+
|
|
74
|
+
canActivate(context: ExecutionContext): boolean {
|
|
75
|
+
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [context.getHandler(), context.getClass()]);
|
|
76
|
+
if (isPublic) return true;
|
|
77
|
+
const req = context.switchToHttp().getRequest();
|
|
78
|
+
const expected = this.config.get<string>('API_KEY');
|
|
79
|
+
if (!expected || req.headers['x-api-key'] !== expected) throw new UnauthorizedException();
|
|
80
|
+
return true;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// usage
|
|
85
|
+
@Public() @Get('health') health() { return { status: 'ok' }; }
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
- `getAllAndOverride` lets route metadata override controller metadata; `getAllAndMerge` combines arrays (e.g. roles).
|
|
89
|
+
- Fail closed: if the secret is not configured, deny.
|
|
90
|
+
- For decorators that take a value (e.g. `@Roles(['admin'])`), prefer the typed form `export const Roles = Reflector.createDecorator<string[]>()`, read with `this.reflector.get(Roles, context.getHandler())`.
|
|
91
|
+
|
|
92
|
+
## Pattern: consistent error responses with errorCode
|
|
93
|
+
|
|
94
|
+
Since v12, HTTP exceptions take a machine-readable `errorCode`, serialized into the default response body. Prefer this over a custom exception hierarchy:
|
|
95
|
+
|
|
96
|
+
```typescript
|
|
97
|
+
throw new BadRequestException('Order has no items', { errorCode: 'ORDER_EMPTY' });
|
|
98
|
+
// → { "message": "Order has no items", "error": "Bad Request", "statusCode": 400, "errorCode": "ORDER_EMPTY" }
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
When every response needs extra fields (path, timestamp), add one global catch-all filter that reads `exception.getResponse()`, keeps `errorCode`, and writes through `HttpAdapterHost`, so it works on every adapter. Read `references/filters-interceptors.md` for the full filter and for the non-HTTP-exception (500) branch.
|
|
102
|
+
|
|
103
|
+
## Routing gotchas
|
|
104
|
+
|
|
105
|
+
- **Route shadowing:** on Express (and the Node adapter), routes match in declaration order, so `@Get(':id')` declared before `@Get('me')` swallows `/me`. Pipes can't fix this, because routing happens first. Fix the order, and enable the v12 diagnostics in `main.ts` so it can't recur silently ([Controllers](https://docs.nestjs.com/controllers)):
|
|
106
|
+
|
|
107
|
+
```typescript
|
|
108
|
+
const app = await NestFactory.create(AppModule, {
|
|
109
|
+
routeConflictPolicy: { duplicate: 'error', shadow: 'warn' }, // or 'error'; checked at app.init()/listen()
|
|
110
|
+
routeResolutionStrategy: 'specificity', // literal segments before :params before wildcards
|
|
111
|
+
});
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Fastify already ranks routes by specificity, so there only `duplicate` matters.
|
|
115
|
+
- **Wildcards** use named parameters: `'cats/*splat'` matches `/cats/x` but **not** `/cats`; `'cats/{*splat}'` matches both. For all routes including `/`, use `forRoutes('{*splat}')`. Bare `*` is deprecated.
|
|
116
|
+
- **`@Res()`** switches the route to library-specific mode: interceptors can't map the response, and you must send it yourself. Use `@Res({ passthrough: true })` to only set cookies or headers.
|
|
117
|
+
- **Fastify:** filters send with `response.send()`, not `.json()`. Middleware signatures differ from Express; the Node adapter uses the Express signature.
|
|
118
|
+
- **Global prefix:** `app.setGlobalPrefix('api', { exclude: [{ path: 'health', method: RequestMethod.GET }] })`.
|
|
119
|
+
- **Default status:** POST returns 201, everything else 200. Change it with `@HttpCode(204)`.
|
|
120
|
+
|
|
121
|
+
## Middleware binding
|
|
122
|
+
|
|
123
|
+
```typescript
|
|
124
|
+
export class AppModule implements NestModule {
|
|
125
|
+
configure(consumer: MiddlewareConsumer) {
|
|
126
|
+
consumer.apply(LoggerMiddleware).exclude({ path: 'health', method: RequestMethod.GET }).forRoutes('{*splat}');
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
Express registers the `json`/`urlencoded` body parsers by default. Set `bodyParser: false` in `NestFactory.create()` before registering your own.
|
|
132
|
+
|
|
133
|
+
## Workflow
|
|
134
|
+
|
|
135
|
+
- [ ] 1. Pick the component from the table, and scaffold it with `nest g`.
|
|
136
|
+
- [ ] 2. Decide the binding scope (route, controller or global). Global means an `APP_*` provider.
|
|
137
|
+
- [ ] 3. For per-route behaviour, add a metadata decorator and read it in the guard or interceptor with `Reflector`.
|
|
138
|
+
- [ ] 4. Update e2e tests: global guards affect every existing test. Override them in tests with `overrideProvider` (nestjs-testing).
|
|
139
|
+
- [ ] 5. Build, lint, run unit and e2e tests, and start the app once if you changed `main.ts`.
|
|
140
|
+
|
|
141
|
+
## Reference files
|
|
142
|
+
|
|
143
|
+
- `references/filters-interceptors.md`: a catch-all exception filter with `HttpAdapterHost`, the `BaseExceptionFilter` extension, interceptor recipes (response mapping, timing, timeout, cache override), and `ExecutionContext` across HTTP/RPC/WS. Read when writing a filter or interceptor.
|
|
144
|
+
- `references/pipes-decorators.md`: built-in `Parse*Pipe` options, custom pipes, `createParamDecorator` with pipes, `applyDecorators` composition, and the `ArgumentMetadata` generic in v12. Read when writing a pipe or a decorator.
|
|
145
|
+
|
|
146
|
+
Sources: [Controllers](https://docs.nestjs.com/controllers) · [Middleware](https://docs.nestjs.com/middleware) · [Guards](https://docs.nestjs.com/guards) · [Interceptors](https://docs.nestjs.com/interceptors) · [Pipes](https://docs.nestjs.com/pipes) · [Exception filters](https://docs.nestjs.com/exception-filters) · [Custom decorators](https://docs.nestjs.com/custom-decorators) · [Request lifecycle](https://docs.nestjs.com/faq/request-lifecycle)
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
# Exception filters and interceptors
|
|
2
|
+
|
|
3
|
+
Sources: [Exception filters](https://docs.nestjs.com/exception-filters) · [Interceptors](https://docs.nestjs.com/interceptors) · [Execution context](https://docs.nestjs.com/fundamentals/execution-context) · [HTTP adapter](https://docs.nestjs.com/faq/http-adapter)
|
|
4
|
+
|
|
5
|
+
## Contents
|
|
6
|
+
- Throwing errors
|
|
7
|
+
- Catch-all filter with a standard error shape (default recipe)
|
|
8
|
+
- Extending the built-in filter
|
|
9
|
+
- Filter rules
|
|
10
|
+
- Interceptor recipes
|
|
11
|
+
- ExecutionContext across transports
|
|
12
|
+
|
|
13
|
+
## Throwing errors
|
|
14
|
+
|
|
15
|
+
```typescript
|
|
16
|
+
throw new NotFoundException(`Order ${id} not found`);
|
|
17
|
+
throw new BadRequestException('Password is too weak', { errorCode: 'WEAK_PASSWORD' }); // v12: errorCode in body
|
|
18
|
+
throw new ConflictException('Email taken', { cause: err, errorCode: 'EMAIL_TAKEN' }); // cause is logged, never serialized
|
|
19
|
+
throw new HttpException('Forbidden', HttpStatus.FORBIDDEN, { errorCode: 'ACCOUNT_SUSPENDED' });
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
The built-in filter does not log `HttpException`s: they are normal flow. Log them yourself in a custom filter if you need to.
|
|
23
|
+
|
|
24
|
+
## Catch-all filter with a standard error shape (default recipe)
|
|
25
|
+
|
|
26
|
+
Platform-agnostic (works on Express, Fastify and the Node adapter) because it replies through `HttpAdapterHost`:
|
|
27
|
+
|
|
28
|
+
```typescript
|
|
29
|
+
import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus, Logger } from '@nestjs/common';
|
|
30
|
+
import { HttpAdapterHost } from '@nestjs/core';
|
|
31
|
+
|
|
32
|
+
@Catch()
|
|
33
|
+
export class AllExceptionsFilter implements ExceptionFilter {
|
|
34
|
+
private readonly logger = new Logger(AllExceptionsFilter.name);
|
|
35
|
+
|
|
36
|
+
constructor(private readonly httpAdapterHost: HttpAdapterHost) {}
|
|
37
|
+
|
|
38
|
+
catch(exception: unknown, host: ArgumentsHost): void {
|
|
39
|
+
const { httpAdapter } = this.httpAdapterHost; // resolve here, not in the constructor
|
|
40
|
+
const ctx = host.switchToHttp();
|
|
41
|
+
const isHttp = exception instanceof HttpException;
|
|
42
|
+
const status = isHttp ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;
|
|
43
|
+
const res = isHttp ? exception.getResponse() : undefined;
|
|
44
|
+
const body = typeof res === 'object' && res !== null ? (res as Record<string, unknown>) : { message: res };
|
|
45
|
+
|
|
46
|
+
if (!isHttp) this.logger.error('Unhandled exception', exception instanceof Error ? exception.stack : String(exception));
|
|
47
|
+
|
|
48
|
+
httpAdapter.reply(ctx.getResponse(), {
|
|
49
|
+
statusCode: status,
|
|
50
|
+
message: isHttp ? body.message : 'Internal server error', // never leak internals on 500
|
|
51
|
+
errorCode: body.errorCode ?? defaultCode(status), // keep v12 errorCode when set
|
|
52
|
+
path: httpAdapter.getRequestUrl(ctx.getRequest()),
|
|
53
|
+
timestamp: new Date().toISOString(),
|
|
54
|
+
}, status);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
`defaultCode(status)` is a small project-owned map (e.g. `404 → 'NOT_FOUND'`), so every error carries a code. Register the filter with `{ provide: APP_FILTER, useClass: AllExceptionsFilter }`. Unknown routes (404) and body-parser errors (400) also pass through it.
|
|
60
|
+
|
|
61
|
+
## Extending the built-in filter
|
|
62
|
+
|
|
63
|
+
```typescript
|
|
64
|
+
@Catch()
|
|
65
|
+
export class AllExceptionsFilter extends BaseExceptionFilter {
|
|
66
|
+
catch(exception: unknown, host: ArgumentsHost) {
|
|
67
|
+
// custom handling for some cases, then:
|
|
68
|
+
super.catch(exception, host);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
- Global use: `app.useGlobalFilters(new AllExceptionsFilter(app.get(HttpAdapterHost).httpAdapter))`, or the `APP_FILTER` provider.
|
|
74
|
+
- Method- and controller-scoped filters extending `BaseExceptionFilter` must not be created with `new`; pass the class: `@UseFilters(MyFilter)`.
|
|
75
|
+
|
|
76
|
+
## Filter rules
|
|
77
|
+
|
|
78
|
+
- Filters resolve route → controller → global. The first one whose `@Catch()` matches handles the exception; it is not passed on (use inheritance to share logic).
|
|
79
|
+
- Registering a catch-all together with a typed filter (e.g. `@Catch(HttpException)`): declare the catch-all **first**, so the typed one still handles its type.
|
|
80
|
+
- Exceptions from middleware reach global filters only.
|
|
81
|
+
- `useGlobalFilters()` doesn't cover gateways or hybrid apps.
|
|
82
|
+
- On Fastify, use `response.send()` and Fastify types if you touch the response directly.
|
|
83
|
+
|
|
84
|
+
## Interceptor recipes
|
|
85
|
+
|
|
86
|
+
```typescript
|
|
87
|
+
@Injectable()
|
|
88
|
+
export class TimingInterceptor implements NestInterceptor {
|
|
89
|
+
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
|
90
|
+
const start = Date.now();
|
|
91
|
+
const res = context.switchToHttp().getResponse();
|
|
92
|
+
return next.handle().pipe(tap(() => res.setHeader('X-Response-Time', `${Date.now() - start}ms`)));
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Wrap every response
|
|
97
|
+
next.handle().pipe(map((data) => ({ data })));
|
|
98
|
+
|
|
99
|
+
// Map errors
|
|
100
|
+
next.handle().pipe(catchError((err) => throwError(() => new BadGatewayException())));
|
|
101
|
+
|
|
102
|
+
// Timeout
|
|
103
|
+
next.handle().pipe(timeout(5000), catchError((err) => err instanceof TimeoutError ? throwError(() => new RequestTimeoutException()) : throwError(() => err)));
|
|
104
|
+
|
|
105
|
+
// Skip the handler (e.g. cache hit)
|
|
106
|
+
if (cached) return of(cached);
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
- Response mapping does not run for handlers that use `@Res()` without `passthrough: true`.
|
|
110
|
+
- Interceptors can inject dependencies. Register globally with `APP_INTERCEPTOR`.
|
|
111
|
+
|
|
112
|
+
## ExecutionContext across transports
|
|
113
|
+
|
|
114
|
+
`context.getType()` returns `'http' | 'rpc' | 'ws'` (GraphQL: `GqlExecutionContext.create(context).getType()` returns `'graphql'`). Branch on it in enhancers shared across transports, and use `switchToHttp()`, `switchToRpc()` or `switchToWs()` accordingly. `context.getHandler()` and `context.getClass()` are the targets for `Reflector` lookups.
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
# Pipes and custom decorators
|
|
2
|
+
|
|
3
|
+
Sources: [Pipes](https://docs.nestjs.com/pipes) · [Custom decorators](https://docs.nestjs.com/custom-decorators) · [Migration guide](https://docs.nestjs.com/migration-guide)
|
|
4
|
+
|
|
5
|
+
For DTO and schema validation (`ValidationPipe`, `StandardSchemaValidationPipe`), use the nestjs-validation-serialization skill.
|
|
6
|
+
|
|
7
|
+
## Contents
|
|
8
|
+
- Built-in pipes
|
|
9
|
+
- Binding pipes
|
|
10
|
+
- Custom pipe
|
|
11
|
+
- Param decorators
|
|
12
|
+
- Composing decorators
|
|
13
|
+
|
|
14
|
+
## Built-in pipes
|
|
15
|
+
|
|
16
|
+
All are exported from `@nestjs/common`:
|
|
17
|
+
|
|
18
|
+
| Pipe | Use |
|
|
19
|
+
| --- | --- |
|
|
20
|
+
| `ParseIntPipe`, `ParseFloatPipe`, `ParseBoolPipe` | Convert a param/query string; 400 if invalid |
|
|
21
|
+
| `ParseUUIDPipe` | Any UUID version by default; restrict with `{ version: '4' }` |
|
|
22
|
+
| `ParseEnumPipe` | `new ParseEnumPipe(Status)` |
|
|
23
|
+
| `ParseArrayPipe` | `new ParseArrayPipe({ items: Number, separator: ',' })` for `?ids=1,2,3` |
|
|
24
|
+
| `ParseDatePipe` | Parse a date string |
|
|
25
|
+
| `DefaultValuePipe` | Put **before** a Parse pipe: `@Query('page', new DefaultValuePipe(1), ParseIntPipe)` |
|
|
26
|
+
| `ParseFilePipe` | File uploads (see the nestjs-http-web-features skill) |
|
|
27
|
+
| `ValidationPipe`, `StandardSchemaValidationPipe` | Body/query validation (nestjs-validation-serialization) |
|
|
28
|
+
|
|
29
|
+
Customize the error: `new ParseIntPipe({ errorHttpStatusCode: HttpStatus.NOT_ACCEPTABLE })`. Optional params: `new ParseIntPipe({ optional: true })`.
|
|
30
|
+
|
|
31
|
+
## Binding pipes
|
|
32
|
+
|
|
33
|
+
```typescript
|
|
34
|
+
@Get(':id') findOne(@Param('id', ParseIntPipe) id: number) {} // parameter (class → DI-instantiated)
|
|
35
|
+
@Get() find(@Query('limit', new DefaultValuePipe(20), ParseIntPipe) limit: number) {}
|
|
36
|
+
@UsePipes(SomePipe) // method or controller
|
|
37
|
+
{ provide: APP_PIPE, useClass: SomePipe } // global, with DI
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Order: global → controller → route → parameter. With several parameters, pipes run on the last parameter first.
|
|
41
|
+
|
|
42
|
+
## Custom pipe
|
|
43
|
+
|
|
44
|
+
```typescript
|
|
45
|
+
@Injectable()
|
|
46
|
+
export class TrimPipe implements PipeTransform<unknown, unknown> {
|
|
47
|
+
transform(value: unknown, metadata: ArgumentMetadata) {
|
|
48
|
+
return typeof value === 'string' ? value.trim() : value;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
- v12 refined pipe transform signatures, and `ArgumentMetadata` takes a generic parameter. Hand-written signatures from older code may need their types adjusted.
|
|
54
|
+
- `metadata.metatype` is `Object` when the parameter is typed with an interface, because interfaces are erased.
|
|
55
|
+
- Throw `BadRequestException` (with an `errorCode` if clients branch on it) for invalid input.
|
|
56
|
+
|
|
57
|
+
## Param decorators
|
|
58
|
+
|
|
59
|
+
```typescript
|
|
60
|
+
export const CurrentUser = createParamDecorator((data: keyof User | undefined, ctx: ExecutionContext) => {
|
|
61
|
+
const user = ctx.switchToHttp().getRequest().user;
|
|
62
|
+
return data ? user?.[data] : user;
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
@Get('me') me(@CurrentUser() user: User) {}
|
|
66
|
+
@Get('email') email(@CurrentUser('email') email: string) {}
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
- `ValidationPipe` skips custom decorators unless `validateCustomDecorators: true` is set.
|
|
70
|
+
- Custom decorators accept the v12 `schema` option for Standard Schema validation, e.g. `@CurrentUser('email', { schema: z.email() })`.
|
|
71
|
+
|
|
72
|
+
## Composing decorators
|
|
73
|
+
|
|
74
|
+
```typescript
|
|
75
|
+
export function Auth(...roles: Role[]) {
|
|
76
|
+
return applyDecorators(SetMetadata('roles', roles), UseGuards(AuthGuard, RolesGuard));
|
|
77
|
+
}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
`@ApiHideProperty()` from `@nestjs/swagger` is not composable with `applyDecorators()`.
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: nestjs-resilience
|
|
3
|
+
description: Hardens NestJS 12 against slow or failing dependencies with the first-party @nestjs/resilience package — ResilienceModule.forRoot defaults and named presets per dependency, entrypoint decorators @Resilience(preset), @Timeout, @Retry (safe methods only unless idempotent: true), @CircuitBreaker, @Bulkhead, @Fallback and @Signal for cooperative cancellation, outbound rate limits, ResilienceService.preset()/create() policy objects inside services and jobs, shared breakers, 504/503 error mapping with Retry-After on every transport, events, combining with @Idempotent, and testing with fake timers and breaker.trip(). Use when adding timeouts, retries with backoff, circuit breakers, fallbacks, bulkheads or concurrency caps around calls to external systems, or when retries pile up, requests hang or a dependency outage takes the app down. Not for the HTTP client's own per-request retries (nestjs-http-client), idempotency keys (nestjs-idempotency) or rate limiting your own API (nestjs-security-hardening).
|
|
4
|
+
compatibility: NestJS 12.x; @nestjs/resilience; optional @nestjs/idempotency
|
|
5
|
+
metadata:
|
|
6
|
+
version: "0.1.0"
|
|
7
|
+
nestjs-major: "12"
|
|
8
|
+
docs-crawled: "2026-11-05"
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
# NestJS resilience (@nestjs/resilience)
|
|
12
|
+
|
|
13
|
+
Prefer `@nestjs/resilience` over hand-rolled `Promise.race` timeouts, retry loops or `opossum` wiring when the package is installed or acceptable.
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm i @nestjs/resilience
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Register once, one preset per dependency
|
|
20
|
+
|
|
21
|
+
```typescript
|
|
22
|
+
@Module({
|
|
23
|
+
imports: [
|
|
24
|
+
IdempotencyModule.forRoot({}), // if used: BEFORE ResilienceModule (first global interceptor runs outermost)
|
|
25
|
+
ResilienceModule.forRoot({
|
|
26
|
+
defaults: { timeout: '5s', retry: { attempts: 3, backoff: { delay: '200ms', maxDelay: '2s' } } }, // fill fields, never turn stages on
|
|
27
|
+
presets: {
|
|
28
|
+
carrier: { timeout: '2s', retry: { attempts: 2 }, circuitBreaker: { failureRateThreshold: 50, minimumCalls: 10, openDuration: '30s' } },
|
|
29
|
+
},
|
|
30
|
+
}),
|
|
31
|
+
],
|
|
32
|
+
})
|
|
33
|
+
export class AppModule {}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
A preset's breaker/bulkhead/outbound rate limit is **shared by name** across every route, handler and service policy using it. Invalid presets or durations fail at bootstrap.
|
|
37
|
+
|
|
38
|
+
## Entrypoints (controllers, resolvers, message handlers, gateways)
|
|
39
|
+
|
|
40
|
+
```typescript
|
|
41
|
+
@Get('quotes')
|
|
42
|
+
@Resilience('carrier')
|
|
43
|
+
@Timeout('1.5s') // per-stage override of the preset
|
|
44
|
+
@Fallback('flatRateQuotes', { handleIf: (e) => e instanceof CircuitOpenError })
|
|
45
|
+
getQuotes(@Query('orderId') orderId: string, @Signal() signal: AbortSignal) {
|
|
46
|
+
return this.shipping.getQuotes(orderId, signal); // pass the signal down to fetch/HTTP client
|
|
47
|
+
}
|
|
48
|
+
flatRateQuotes() { return this.shipping.flatRateQuotes(); } // cheap; never calls the failing dependency
|
|
49
|
+
|
|
50
|
+
@Post('shipments')
|
|
51
|
+
@Idempotent() // dedupes client retries (nestjs-idempotency)
|
|
52
|
+
@Resilience('carrier')
|
|
53
|
+
@Retry({ idempotent: true }) // allow server-side re-runs: carrier dedupes by reference
|
|
54
|
+
createShipment(@Body('orderId') orderId: string, @Signal() signal: AbortSignal) { … }
|
|
55
|
+
|
|
56
|
+
@Get('export') @Bulkhead({ maxConcurrent: 2, maxQueue: 3, queueTimeout: '10s' })
|
|
57
|
+
export() { return this.orders.exportCsv(); }
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
- Timeouts are **per attempt**; worst case ≈ attempts × timeout + backoff — keep it under client and load-balancer timeouts.
|
|
61
|
+
- Retries only re-run safe operations (GET/HEAD/OPTIONS, GraphQL queries). On message/event/WS handlers only a handler-level `@Retry()` applies. Guards and middleware run once; pipes, inner interceptors and the handler re-run.
|
|
62
|
+
- Client errors (4xx `HttpException`s) are not failures: not retried, not counted by breakers, not replaced by fallbacks.
|
|
63
|
+
- Responses: timeout → **504** `TIMEOUT`; open breaker → **503** `CIRCUIT_OPEN` + `Retry-After`; full bulkhead → 503 `BULKHEAD_FULL`; outbound limit → 503 `RATE_LIMITED`. RPC/WS get `RpcException`/`WsException` payloads; GraphQL gets `extensions.code/httpStatus/retryAfter`.
|
|
64
|
+
- Code that can't take the signal as a parameter can inject `ResilienceContext` (`signal`, `attempt`).
|
|
65
|
+
- Hybrid apps: `connectMicroservice(opts, { inheritAppConfig: true })`.
|
|
66
|
+
|
|
67
|
+
## Inside services and jobs: policy objects
|
|
68
|
+
|
|
69
|
+
Decorators on provider methods do nothing (bootstrap warns). Use a policy:
|
|
70
|
+
|
|
71
|
+
```typescript
|
|
72
|
+
private readonly carrier = this.resilience.preset('carrier'); // create once; shares the route's breaker
|
|
73
|
+
|
|
74
|
+
const quotes = await this.carrier.execute(({ signal }) => this.client.getQuotes(order, signal), { source: 'RepricingService' });
|
|
75
|
+
// catch CircuitOpenError → stop the batch instead of waiting on every item
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Policy retries **always** apply (no HTTP method to check): only wrap repeatable calls. Ad-hoc: `resilience.create(options, name)`.
|
|
79
|
+
|
|
80
|
+
## Gotchas
|
|
81
|
+
|
|
82
|
+
- Retry at **one** layer: turn off retries in the HTTP client/SDK underneath (`retry: false` in `@nestjs/http-client`).
|
|
83
|
+
- Every breaker needs a timeout (hanging calls are never counted).
|
|
84
|
+
- State is per process: each instance has its own breakers, bulkheads and rate limits.
|
|
85
|
+
- Tune `minimumCalls`, `openDuration`, `recordIf` per dependency.
|
|
86
|
+
- Register an idempotency store in production when pairing with `@Idempotent()`.
|
|
87
|
+
|
|
88
|
+
## Observability
|
|
89
|
+
|
|
90
|
+
Subscribe to `ResilienceEvents.events$` (`retry`, `timeout`, `circuit-open/half-open/closed`, `circuit-rejected`, `bulkhead-rejected`, `rate-limited`, `fallback`) or diagnostics channels `nestjs:resilience:<type>`; log/alert on breaker transitions and bulkhead rejections. Inspect/force breakers with `resilience.circuitBreaker('carrier')` (`state`, `stats`, `trip()`, `reset()`).
|
|
91
|
+
|
|
92
|
+
## Testing
|
|
93
|
+
|
|
94
|
+
```typescript
|
|
95
|
+
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); // keep real I/O for supertest
|
|
96
|
+
carrier.getQuotes.mockImplementation((_o, signal) => new Promise((_, rej) => signal.addEventListener('abort', () => rej(signal.reason))));
|
|
97
|
+
await vi.waitFor(() => expect(carrier.getQuotes).toHaveBeenCalled());
|
|
98
|
+
await vi.advanceTimersByTimeAsync(5_000); // → 504, signal aborted, 2 calls
|
|
99
|
+
app.get(ResilienceService).circuitBreaker('carrier').trip(); // test open state directly
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Override options with `overrideProvider(RESILIENCE_MODULE_OPTIONS)`. Each test app starts with fresh breaker state.
|
|
103
|
+
|
|
104
|
+
## Workflow
|
|
105
|
+
|
|
106
|
+
- [ ] 1. Install; one preset per external dependency with timeout + breaker (+ retry for safe calls).
|
|
107
|
+
- [ ] 2. Decorate entrypoints; pass `@Signal()` through every I/O call; add cheap fallbacks where degraded answers exist.
|
|
108
|
+
- [ ] 3. Mark only truly repeatable unsafe routes `idempotent: true`, combined with `@Idempotent()`.
|
|
109
|
+
- [ ] 4. Use policy objects in services/jobs; remove nested retries.
|
|
110
|
+
- [ ] 5. Event logging/alerts; fake-timer tests. Build, lint, run tests, start the app.
|
|
111
|
+
|
|
112
|
+
## Reference files
|
|
113
|
+
|
|
114
|
+
- `references/resilience-reference.md`: decorator options and defaults, module options, preset fields, outbound rate limit, events and errors tables, transport payloads. Read when tuning options.
|
|
115
|
+
|
|
116
|
+
Sources: [Resilience](https://docs.nestjs.com/reliability/resilience)
|