init
This commit is contained in:
@@ -0,0 +1,200 @@
|
||||
# HTTP details
|
||||
|
||||
Docs: https://docs.nestjs.com/controllers.md, https://docs.nestjs.com/exception-filters.md, https://docs.nestjs.com/interceptors.md, https://docs.nestjs.com/http/versioning.md, https://docs.nestjs.com/faq/raw-body.md, https://docs.nestjs.com/http/server-sent-events.md
|
||||
|
||||
The snippets on this page were run on Nest 12.5 with the Express adapter.
|
||||
|
||||
## Status codes
|
||||
|
||||
```typescript
|
||||
@Post('login')
|
||||
@HttpCode(200) // @Post() defaults to 201 Created
|
||||
login(@Body({ schema: credentialsSchema }) body: Credentials) { ... }
|
||||
|
||||
@Delete(':id')
|
||||
@HttpCode(204) // no body
|
||||
remove(@Param('id', { schema: id }) noteId: number) { return this.notes.remove(noteId); }
|
||||
```
|
||||
|
||||
For a status decided at run time, inject the response with passthrough, so Nest still serializes the return value: `@Res({ passthrough: true }) res: Response` and `res.status(202)`.
|
||||
|
||||
## Errors
|
||||
|
||||
Throw the built-in exceptions (`BadRequestException`, `UnauthorizedException`, `ForbiddenException`, `NotFoundException`, `ConflictException`, `UnprocessableEntityException`, `HttpException` for any other code). Nest answers them as `{ "statusCode": 404, "message": "...", "error": "Not Found" }`; any other thrown error is a 500 with `"Internal server error"`.
|
||||
|
||||
When the API contract fixes a different error body, map every `HttpException` in one global filter. Validation pipes and guards (including `@nestjs/authentication`'s and `@nestjs/throttler`'s) throw `HttpException`s, so they're covered:
|
||||
|
||||
```typescript
|
||||
// src/common/http-error.filter.ts
|
||||
import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus, Logger } from '@nestjs/common';
|
||||
import type { Response } from 'express';
|
||||
|
||||
@Catch()
|
||||
export class HttpErrorFilter implements ExceptionFilter {
|
||||
private readonly logger = new Logger(HttpErrorFilter.name);
|
||||
|
||||
catch(exception: unknown, host: ArgumentsHost) {
|
||||
const res = host.switchToHttp().getResponse<Response>();
|
||||
if (exception instanceof HttpException) {
|
||||
const body = exception.getResponse();
|
||||
const message =
|
||||
typeof body === 'string' ? body : [(body as { message?: string | string[] }).message ?? exception.message].flat().join('; ');
|
||||
res.status(exception.getStatus()).json({ code: exception.getStatus(), detail: message }); // the contract's shape
|
||||
return;
|
||||
}
|
||||
this.logger.error(exception);
|
||||
res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ code: 500, detail: 'Internal server error' });
|
||||
}
|
||||
}
|
||||
|
||||
// main.ts
|
||||
app.useGlobalFilters(new HttpErrorFilter());
|
||||
```
|
||||
|
||||
Response headers set by the thrower (e.g. `WWW-Authenticate` from the authentication guard, `Retry-After` from the throttler) are already on the response when the filter runs, so they're kept.
|
||||
|
||||
This filter is for the Express adapter (the default). On Fastify, use `res.status(...).send(...)` with `FastifyReply`, or `HttpAdapterHost`'s `httpAdapter.reply()` for both.
|
||||
|
||||
An unparseable JSON body is a 400 from the body parser, which reaches the filter as a `BadRequestException`.
|
||||
|
||||
## Bootstrap options that change HTTP behaviour
|
||||
|
||||
```typescript
|
||||
// main.ts
|
||||
import type { NestExpressApplication } from '@nestjs/platform-express';
|
||||
|
||||
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
|
||||
rawBody: true, // keeps req.rawBody (a Buffer) for webhook signature checks
|
||||
});
|
||||
app.useBodyParser('json', { limit: '100kb' }); // larger bodies: 413
|
||||
app.setGlobalPrefix('api', { exclude: ['health'] }); // /api/notes, but /health stays at the root
|
||||
app.enableVersioning({ type: VersioningType.URI, defaultVersion: ['1', VERSION_NEUTRAL] }); // /api/v1/notes and /api/notes
|
||||
app.set('trust proxy', 1); // Express: behind one proxy, req.ip is the client's address, not the proxy's
|
||||
await app.listen(process.env.PORT ?? 3000);
|
||||
```
|
||||
|
||||
- `setGlobalPrefix()` moves every controller route, health checks included, unless you `exclude` them; probes and load balancers then get 404s. `SwaggerModule.setup()` is not prefixed unless you pass `useGlobalPrefix: true`.
|
||||
- The JSON body limit defaults to 100 kB in Express. Raise it per need, not globally to megabytes.
|
||||
- Verify a webhook signature over `req.rawBody` (`@Req() req: RawBodyRequest<Request>`, with `import type { RawBodyRequest }`), never over `JSON.stringify(body)`, which is not the bytes the sender signed.
|
||||
- On the Node adapter, these are constructor options: `new NodeAdapter({ trustProxy: 'loopback' })` (a name or address list, no hop count), `querystringParser`, `maxParamLength`; `useBodyParser()` works the same (checked). Fastify: `new FastifyAdapter({ trustProxy: true })`.
|
||||
- Without `trust proxy`, every client behind a load balancer has the proxy's IP, so IP rate limits and logs lump everyone together. Trust only as many hops as you actually have.
|
||||
|
||||
## Request IDs
|
||||
|
||||
```typescript
|
||||
@Injectable()
|
||||
export class RequestIdInterceptor implements NestInterceptor {
|
||||
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
||||
const http = context.switchToHttp();
|
||||
const req = http.getRequest<Request>();
|
||||
const res = http.getResponse<Response>();
|
||||
const incoming = req.header('x-request-id');
|
||||
const id = incoming && /^[\w.-]{1,128}$/.test(incoming) ? incoming : randomUUID();
|
||||
res.setHeader('X-Request-Id', id);
|
||||
return next.handle();
|
||||
}
|
||||
}
|
||||
// AppModule providers: { provide: APP_INTERCEPTOR, useClass: RequestIdInterceptor }
|
||||
```
|
||||
|
||||
- Validate an incoming id before echoing it (length, characters): it lands in logs and response headers.
|
||||
- An interceptor runs after guards, so a request a guard refuses (401, 403, 429) gets no header from it. If every response must carry one, set it in middleware (`app.use((req, res, next) => { ...; next(); })` in `main.ts`), which runs first.
|
||||
- NestJS Observe adopts a well-formed incoming `x-request-id` as the trace id and stamps it on log lines (`nestjs-production`).
|
||||
|
||||
## Reading the request
|
||||
|
||||
- `@Param('id')`, `@Query('cursor')`, `@Body()`, `@Headers('x-tenant-id')`, `@Ip()`: each with an optional `{ schema }` or pipes.
|
||||
- Your own: `export const TenantId = createParamDecorator((_: unknown, ctx: ExecutionContext) => ctx.switchToHttp().getRequest().headers['x-tenant-id'])`, used as `@TenantId({ schema: z.uuid() }) tenantId: string`.
|
||||
- Avoid `@Res()` without `passthrough: true`: you then own the whole response, and interceptors, `@HttpCode()` and serialization stop applying to that route.
|
||||
|
||||
## Response headers
|
||||
|
||||
`@Header('Cache-Control', 'no-store')` for static ones; dynamic ones through `@Res({ passthrough: true }) res` and `res.setHeader(...)`, or an interceptor. Headers set before an exception is thrown survive it (the guard's `WWW-Authenticate`, the throttler's `Retry-After`).
|
||||
|
||||
## Lists
|
||||
|
||||
Page with a cursor, not an offset: `WHERE id > :cursor ORDER BY id LIMIT :limit + 1`. The extra row says whether there's a next page without a `COUNT(*)`, and inserts don't shift pages (`nestjs-data` has the query). Cap `limit` in the schema (`z.coerce.number().int().min(1).max(100).default(20)`), and return the next cursor (`{ items, nextCursor }`) or a `Link` header, whichever the contract names.
|
||||
|
||||
## Routing and serialization surprises (checked)
|
||||
|
||||
- Named wildcards (Nest 11+, Express 5): with `@Get('files/{*path}')`, `/files/` and `/files/a/b` match (`path` is `['a', 'b']`) and `/files` is a 404; with `@Get('docs/*path')`, `/docs/a` matches and `/docs/` and `/docs` are 404s.
|
||||
- Query strings: `?filter[status]=done` arrives as `{ "filter[status]": "done" }`; after `app.set('query parser', 'extended')`, as `{ "filter": { "status": "done" } }`.
|
||||
|
||||
- Express adapter: `@Get(':id')` declared before `@Get('search')` in the same controller: `GET /notes/search` reaches `findOne` with `id = 'search'`. Static paths first. Node adapter, same controller: `/notes/search` reaches `search`, because it matches by specificity (both checked).
|
||||
- `ClassSerializerInterceptor` + `@Exclude() passwordHash` on an entity class: a returned instance goes out as `{"id":1,"email":"a@x.io"}`, but a plain object with the same fields goes out with `passwordHash`. Drizzle rows and most query results are plain objects.
|
||||
- An interceptor doing `map((data) => ({ data }))` turns an SSE event `{ data: { hello: 1 } }` into `data: {"data":{"hello":1}}`, with the event's `type` and `id` buried inside. Exclude `@Sse()` and streaming routes from response-wrapping interceptors.
|
||||
|
||||
## Ids that aren't numbers
|
||||
|
||||
`ParseIntPipe` and `z.coerce.number()` answer 400 for `/notes/abc`. When the contract treats such an id as "not found", give the pipe that status (checked: `/items/abc` answers 404, `/items/7` gives the number 7):
|
||||
|
||||
```typescript
|
||||
@Get(':id')
|
||||
findOne(@Param('id', new ParseIntPipe({ errorHttpStatusCode: HttpStatus.NOT_FOUND })) id: number) { ... }
|
||||
```
|
||||
|
||||
Or parse it yourself, e.g. to reject values beyond `Number.MAX_SAFE_INTEGER` too:
|
||||
|
||||
```typescript
|
||||
@Get(':id')
|
||||
findOne(@Param('id') raw: string) {
|
||||
const id = /^\d+$/.test(raw) ? Number(raw) : NaN;
|
||||
if (!Number.isSafeInteger(id)) throw new NotFoundException('Note not found');
|
||||
return this.notes.findOne(id);
|
||||
}
|
||||
```
|
||||
|
||||
## Server-Sent Events
|
||||
|
||||
```typescript
|
||||
import { Controller, MessageEvent, Sse } from '@nestjs/common';
|
||||
import { CurrentUser } from '@nestjs/authentication';
|
||||
import { Observable, finalize, map } from 'rxjs';
|
||||
|
||||
@Controller()
|
||||
export class EventsController {
|
||||
constructor(private readonly events: EventsService) {}
|
||||
|
||||
@Sse('events')
|
||||
stream(@CurrentUser() user: User): Observable<MessageEvent> {
|
||||
return this.events.forUser(user.id).pipe(
|
||||
map((e): MessageEvent => ({ type: e.type, data: e.payload })), // event name; data is a string or an object
|
||||
finalize(() => this.events.release(user.id)), // runs on disconnect too
|
||||
);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- An `EventsService` holding a `Subject` per user (or one `Subject` filtered by user id) is enough inside one process; across instances, use Redis pub/sub or a queue.
|
||||
- Guards and the user are resolved once, when the stream opens. A revoked token, key or session, or a deleted user, keeps receiving events until the stream is completed: see "Ending streams on revocation" below.
|
||||
- To send a first event at once (some clients wait for one), start the observable with it: `startWith({ type: 'ready', data: {} })`.
|
||||
- For keep-alive comments or full control of the bytes, a handler can also return a web `ReadableStream` or an async generator: https://docs.nestjs.com/http/streaming-responses.md
|
||||
- Shutting down with open streams: the HTTP server waits for open connections, so with a stream open `SIGTERM` doesn't stop the app (checked on Nest 12.5: still running 5 s later). Complete the streams in `beforeApplicationShutdown()`, which runs before the server closes (with `app.enableShutdownHooks()`); then it exits at once. `NestFactory.create(AppModule, { forceCloseConnections: true })` is the blunt alternative.
|
||||
|
||||
## Ending streams on revocation
|
||||
|
||||
```typescript
|
||||
@Injectable()
|
||||
export class StreamRevocations {
|
||||
private readonly revoked = new Subject<string>();
|
||||
/** Emits when `credentialId` is revoked. */
|
||||
until(credentialId: string) {
|
||||
return this.revoked.pipe(filter((id) => id === credentialId));
|
||||
}
|
||||
revoke(credentialId: string) {
|
||||
this.revoked.next(credentialId);
|
||||
}
|
||||
}
|
||||
|
||||
// in the SSE handler: the response ends when this key (or session, or user) is revoked
|
||||
return this.events.forUser(user.id).pipe(
|
||||
map((e): MessageEvent => ({ type: e.type, data: e.payload })),
|
||||
takeUntil(this.revocations.until(keyId)),
|
||||
finalize(() => this.events.release(user.id)),
|
||||
);
|
||||
|
||||
// wherever the credential is revoked: API key deleted, session ended, user deleted
|
||||
this.revocations.revoke(keyId);
|
||||
```
|
||||
|
||||
Checked: after `DELETE`, the open response ends and `finalize()` runs. With several instances, publish revocations over Redis (or poll the credential's status) so the instance holding the stream hears it.
|
||||
@@ -0,0 +1,70 @@
|
||||
# Modules, providers and scopes
|
||||
|
||||
Docs: https://docs.nestjs.com/modules.md, https://docs.nestjs.com/fundamentals/custom-providers.md, https://docs.nestjs.com/fundamentals/injection-scopes.md, https://docs.nestjs.com/faq/common-errors.md. Each behaviour marked "checked" was run on Nest 12.5.
|
||||
|
||||
## One instance per module that lists it
|
||||
|
||||
```typescript
|
||||
@Module({ providers: [Counter, A], exports: [A] }) class ModA {}
|
||||
@Module({ providers: [Counter, B], exports: [B] }) class ModB {}
|
||||
// A and B get two different Counter instances: state set through one isn't seen by the other (checked).
|
||||
```
|
||||
|
||||
Share a provider by listing it in one module, exporting it, and importing that module wherever it's injected:
|
||||
|
||||
```typescript
|
||||
@Module({ providers: [Counter], exports: [Counter] }) class CounterModule {}
|
||||
@Module({ imports: [CounterModule], providers: [A], exports: [A] }) class ModA {}
|
||||
```
|
||||
|
||||
`@Global()` makes a module's exports injectable everywhere without importing it. Keep it for app-wide infrastructure (config, database, logging); a global feature module hides who depends on what.
|
||||
|
||||
## Dynamic modules
|
||||
|
||||
`XModule.forRoot(options)` configures a package once, in the root module; `XModule.forFeature(...)` (TypeORM repositories, for example) or a plain import gives feature modules what they need. Use `forRootAsync({ imports: [ConfigModule], inject: [ConfigService], useFactory: (config) => ({...}) })` when options come from configuration; `forRoot({...})` evaluates its argument when the file is imported.
|
||||
|
||||
## Tokens for things that aren't classes
|
||||
|
||||
```typescript
|
||||
export const NOTES_REPOSITORY = Symbol('NOTES_REPOSITORY');
|
||||
|
||||
@Module({
|
||||
providers: [
|
||||
{ provide: NOTES_REPOSITORY, useClass: SqlNotesRepository }, // or useValue / useFactory
|
||||
NotesService,
|
||||
],
|
||||
})
|
||||
export class NotesModule {}
|
||||
|
||||
@Injectable()
|
||||
export class NotesService {
|
||||
constructor(@Inject(NOTES_REPOSITORY) private readonly repository: NotesRepository) {} // NotesRepository: an interface
|
||||
}
|
||||
```
|
||||
|
||||
An interface or type alias doesn't exist at run time, so injecting one without `@Inject(token)` fails at startup with `?` at that parameter's index.
|
||||
|
||||
## `import type` and dependency injection
|
||||
|
||||
Nest reads constructor parameter types from decorator metadata at run time. `import type { NotesService }` erases it, and the app stops with `Nest can't resolve dependencies of the NotesController (?). Please make sure that the argument Function at index [0] ...` (checked). Use a value import for every class you inject, and turn off auto-fixes (`consistent-type-imports`) that rewrite them.
|
||||
|
||||
The reverse also holds under `isolatedModules` (the scaffold's default): a type used only in a decorated signature, such as `Request` from express or `RawBodyRequest`, must be imported with `import type`, or `tsc` stops with TS1272 (checked).
|
||||
|
||||
## Scopes
|
||||
|
||||
- Providers are singletons by default: one instance for the app, created at startup. Keep per-request data out of their fields.
|
||||
- `@Injectable({ scope: Scope.REQUEST })` creates an instance per request, and the scope bubbles up: every provider and controller that injects it becomes request-scoped too, with an instance per request for the whole chain.
|
||||
- Lifecycle hooks (`onModuleInit`, `onApplicationBootstrap`, `onModuleDestroy`, ...) are never called on request-scoped classes (checked: 0 calls).
|
||||
- A `@Cron()`, `@Interval()` or `@Timeout()` method in a class that depends on a request-scoped provider is never scheduled: `@nestjs/schedule` only schedules classes whose dependency tree is static, and logs a warning for the rest.
|
||||
- WebSocket gateways (Nest 12+) can depend on request-scoped providers: the scope is then the connection, one instance per connected socket, so it can hold per-connection state (docs: `/websockets/gateways`, "Request-scoped gateways").
|
||||
- For "who is calling" inside services, inject a context instead of a request-scoped provider: `AuthenticationContext` from `@nestjs/authentication`, or `AsyncLocalStorage` (`nestjs-cls`, docs: `/recipes/async-local-storage`).
|
||||
|
||||
## Circular dependencies
|
||||
|
||||
Two modules that import each other, or two providers that inject each other, fail at startup or inject `undefined`. Move what both need into a third module. `forwardRef(() => OtherModule)` on both sides works, but it hides a design problem and makes the order of initialization matter.
|
||||
|
||||
## Startup work
|
||||
|
||||
- `onModuleInit()`: after the module's providers are created; `onApplicationBootstrap()`: after every module is initialized. Both may be `async`, and Nest waits for them before listening.
|
||||
- Work that needs another module's provider to be ready goes in `onApplicationBootstrap()`.
|
||||
- An async factory (`useFactory: async () => ...`) delays everything that injects it until it resolves: the place for "connect, then migrate".
|
||||
@@ -0,0 +1,81 @@
|
||||
# Structure: where code goes, how to organize modules, what to avoid
|
||||
|
||||
Conventions an experienced Nest team follows, and the ones coding agents most often get wrong.
|
||||
|
||||
## Where logic goes
|
||||
|
||||
1. **Controllers do HTTP only**: read params, call one service method, set status codes and headers. No business rules, no queries.
|
||||
2. **Services hold the use cases and rules** ("an archived note can't be edited"). They don't know about HTTP: no `Request`, `Response` or `@Res()` in them, so a queue worker or a CLI command can call them too.
|
||||
3. **Data access lives in repositories** (your own class, or the ORM's repository behind a service), never in controllers, and never as raw SQL scattered across services.
|
||||
4. **Shape at the edge, rules in the service.** Types, lengths and formats go in the schema or DTO; checks that need the database ("email taken", "over quota") go in the service.
|
||||
5. **Permissions:** route-level checks with `@Can()`, record-level checks in the service after loading the record (`nestjs-auth`).
|
||||
6. **Response shapes in one place per resource**: a mapper function or a response class, not ad hoc spreads in each handler. Never return ORM entities or rows directly: they leak password hashes, internal columns and lazy relations.
|
||||
7. **Cross-cutting concerns go in the building block made for them:** authentication and access in guards; logging, timing and response mapping in interceptors; the error body in one exception filter; parsing and transformation in pipes; raw request work before routing in middleware. Business rules go in none of them.
|
||||
8. **Services throw Nest exceptions** (`NotFoundException`, `ConflictException`, ...) instead of returning `null` or error codes that every controller has to translate.
|
||||
|
||||
## Modules and features
|
||||
|
||||
9. **One module per feature or business capability** (`notes`, `billing`, `identity`), never per technical layer: no top-level `controllers/`, `services/` or `repositories/` folders.
|
||||
10. **A feature folder holds everything about it:** module, controller, service, repository, DTOs or schemas, policy, and its tests. Everything about notes is in `src/notes/`.
|
||||
11. **Export as little as possible.** A module's `exports` are its public API: only what other modules actually inject.
|
||||
12. **Reading another feature's table:** register that table's repository in your own module (`TypeOrmModule.forFeature([Note])` in the module that needs it; with Drizzle, import the table and query it) rather than importing the other feature's module. Feature modules importing each other is how circular module dependencies start. Go through the owning feature's service only when the operation has to run that feature's rules or side effects.
|
||||
13. **Shared infrastructure gets its own modules** (database, config, mail, logging), imported where needed. Avoid `@Global()` in general, and always for feature modules: a global module hides who depends on what, and makes modules impossible to test or move on their own. Packages that register themselves globally (`ConfigModule` with `isGlobal`, the database module) are the usual exception.
|
||||
14. **No catch-all `SharedModule` or `CommonModule`** that everything imports. Pure helpers go in plain files; anything with dependencies goes in a small, focused module.
|
||||
15. **The root `AppModule` composes**: feature modules, infrastructure modules and app-wide providers (`APP_GUARD`, `APP_FILTER`, ...). No feature controllers or services of its own.
|
||||
16. **A cycle between feature modules means a boundary is wrong.** Extract what both need into a third module, register the repository you need (item 12), or communicate through events. `forwardRef()` is the last resort.
|
||||
17. **Side effects across features** ("when a user is deleted, cancel their reminders"): a domain event (`@nestjs/event-emitter`) or a queued job when it needn't happen in the same transaction; a direct service call when it must.
|
||||
|
||||
## Configuration
|
||||
|
||||
18. All configuration through `@nestjs/config` with a schema validated at startup; no `process.env` reads scattered through services.
|
||||
19. Typed namespaces (`registerAs('database', () => ({...}))`, injected with `@Inject(databaseConfig.KEY)`) instead of string keys everywhere.
|
||||
20. Module options from configuration: `forRootAsync({ inject: [ConfigService], useFactory })`, not `forRoot({ secret: process.env.X })`.
|
||||
21. Secrets never in code or committed files; a separate key per environment.
|
||||
|
||||
## Code style
|
||||
|
||||
22. **Constructor injection only.** `new SomeService()` inside a provider bypasses the container: its dependencies, lifecycle hooks and test overrides stop applying.
|
||||
23. **Abstractions where there's a second implementation or a test seam** (a payment provider, a mailer): an interface plus a token. Not an interface and token for every class.
|
||||
24. **Providers are stateless singletons.** Per-request data comes from arguments or a context service (`AuthenticationContext`), never from fields.
|
||||
25. **Small, single-purpose services.** Split one that injects many unrelated collaborators, or whose methods share nothing.
|
||||
26. **Nest's naming:** `notes.module.ts`/`NotesModule`, `notes.controller.ts`/`NotesController`, `notes.service.ts`/`NotesService`, `notes.service.spec.ts`; DTO classes end in `Dto` (`CreateNoteDto`, `UpdateNoteDto`, `NoteResponseDto`) in `create-note.dto.ts`, and schemas in `notes.schemas.ts` (`createNoteSchema`, type `CreateNote`). The CLI, tools and other developers look for these names.
|
||||
27. **DTOs per use case**: create, update and response are separate types, not one entity class used as input, output and table at once. Blurring them is how a read-then-`save()` update resurrects deleted rows and how password hashes reach responses.
|
||||
|
||||
## Performance
|
||||
|
||||
28. **For throughput, use the Node adapter.** `@nestjs/platform-node`'s `NodeAdapter` (Nest 12.3+) is the fastest adapter: about 50% more requests per second than Express and about 5% more than Fastify in Nest's benchmarks, with Express-style request/response helpers, so most Express middleware works unchanged. Express (the scaffold's default) stays the safe choice when the app relies on Express APIs the Node adapter doesn't implement (`res.render()`, `res.download()`, ...); Fastify when you need its plugins. Docs: `/http/performance`.
|
||||
- Adapter differences to know (checked on 12.5): the Node and Fastify adapters match routes by specificity, Express in declaration order; trusted proxies are a constructor option on Node and Fastify (`new NodeAdapter({ trustProxy: 'loopback' })`), `app.set('trust proxy', 1)` on Express; e2e tests must pass the same adapter to `createNestApplication(new NodeAdapter())`, or they run on Express.
|
||||
- The adapter is a small part of each request: a route waiting on a database gains little. It matters for light routes at high request rates.
|
||||
29. **Never block the event loop.** One Node process serves every request on one thread: a CPU-heavy loop (image or PDF processing, big JSON transforms, compression, synchronous crypto such as `bcrypt.hashSync`/`scryptSync`, regexes on untrusted input) stalls every other request on the instance. Move such work to a queue worker (`@nestjs/bullmq`) or a `worker_threads` pool, use the async APIs, and stream large payloads instead of building them in memory.
|
||||
|
||||
## Errors and logs
|
||||
|
||||
30. One global exception filter for the error body; log unexpected errors there, once.
|
||||
31. Don't catch just to log and rethrow. Catch to handle (retry, fall back, map to a domain error) or to add context.
|
||||
32. A `Logger` per class (`new Logger(NotesService.name)`) with structured params; never `console.log`.
|
||||
33. Instrument from day one (NestJS Observe, `nestjs-production`), not after the first incident.
|
||||
|
||||
## What to avoid
|
||||
|
||||
34. Request-scoped providers for convenience: the scope spreads to every dependent and costs an instance chain per request.
|
||||
35. `@Res()` without `passthrough: true`.
|
||||
36. Business rules in guards, interceptors, middleware or custom decorators: hidden, hard to find, hard to test. A decorator carries metadata or extracts a parameter; it doesn't query the database.
|
||||
37. "God" services (`UsersService` doing sign-in, profile, billing and email).
|
||||
38. Copy-pasted helpers across features; extract them once.
|
||||
39. Deep inheritance between services or controllers; compose instead.
|
||||
40. Architecture beyond the problem: CQRS, ports-and-adapters layers, or repositories wrapping repositories in a small app. Start with module, controller, service and repository; add structure when a feature needs it.
|
||||
41. Microservices before they're needed. A modular monolith with clean module boundaries (items 9-17) splits later.
|
||||
42. `synchronize: true` in production, `any`-typed bodies, "temporarily" disabled validation, TypeScript `strict` off.
|
||||
43. Barrel files (`index.ts` re-exporting a feature) inside an app: they make circular imports easy, which show up as `undefined` providers at startup.
|
||||
|
||||
## Testing and change
|
||||
|
||||
44. Rules live in services and policies, so they're unit-testable without HTTP (`nestjs-testing`).
|
||||
45. A feature module boots on its own in a test with its dependencies stubbed. If it can't, its boundaries leak.
|
||||
46. One change carries its whole feature: module wiring, schema or DTO, migration, tests and the OpenAPI description together.
|
||||
|
||||
## Growing
|
||||
|
||||
47. Dozens of modules: group them by domain (`src/catalog/products`, `src/catalog/categories`); module boundaries become ownership lines between teams.
|
||||
48. Code shared between several apps (an API and a worker) goes in workspace libraries (`nest g library`); one app doesn't need libraries.
|
||||
49. External clients: version the API (`app.enableVersioning()`), and never change a released response shape silently.
|
||||
@@ -0,0 +1,117 @@
|
||||
# Validation in Nest 12
|
||||
|
||||
Docs: https://docs.nestjs.com/application/validation.md
|
||||
|
||||
Two pipes, both in `@nestjs/common`:
|
||||
|
||||
- `StandardSchemaValidationPipe` (Nest 12.1+) validates parameters that declare a `schema`: Zod, Valibot, ArkType or any [Standard Schema](https://standardschema.dev/) library. No classes, no reflection metadata; the parameter's type is inferred from the schema.
|
||||
- `ValidationPipe` validates parameters typed with a class decorated with class-validator rules (`npm i class-validator class-transformer`).
|
||||
|
||||
Each pipe ignores the other's parameters, so both can be bound at once while an app moves from one to the other.
|
||||
|
||||
## Schemas (Zod shown)
|
||||
|
||||
```typescript
|
||||
// main.ts
|
||||
import { StandardSchemaValidationPipe } from '@nestjs/common';
|
||||
app.useGlobalPipes(new StandardSchemaValidationPipe());
|
||||
```
|
||||
|
||||
```typescript
|
||||
// notes.schemas.ts
|
||||
import { z } from 'zod';
|
||||
|
||||
export const createNoteSchema = z.object({ title: z.string().trim().min(1).max(200) });
|
||||
export type CreateNote = z.infer<typeof createNoteSchema>;
|
||||
|
||||
// Any subset; a field that's present must be valid, and null is rejected.
|
||||
export const updateNoteSchema = z
|
||||
.object({ title: z.string().trim().min(1).max(200), archived: z.boolean() })
|
||||
.partial();
|
||||
export type UpdateNote = z.infer<typeof updateNoteSchema>;
|
||||
|
||||
export const listQuerySchema = z.object({
|
||||
limit: z.coerce.number().int().min(1).max(100).default(20),
|
||||
cursor: z.string().optional(),
|
||||
});
|
||||
```
|
||||
|
||||
```typescript
|
||||
// notes.controller.ts
|
||||
import { Body, Controller, Get, Param, Patch, Post, Query } from '@nestjs/common';
|
||||
import { z } from 'zod';
|
||||
|
||||
const id = z.coerce.number().int().positive();
|
||||
|
||||
@Controller('notes')
|
||||
export class NotesController {
|
||||
constructor(private readonly notes: NotesService) {}
|
||||
|
||||
@Post()
|
||||
create(@Body({ schema: createNoteSchema }) body: CreateNote) {
|
||||
return this.notes.create(body);
|
||||
}
|
||||
|
||||
@Get()
|
||||
list(@Query({ schema: listQuerySchema }) query: z.infer<typeof listQuerySchema>) {
|
||||
return this.notes.list(query);
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
update(@Param('id', { schema: id }) noteId: number, @Body({ schema: updateNoteSchema }) body: UpdateNote) {
|
||||
return this.notes.update(noteId, body);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- `schema` works on `@Body()`, `@Query()`, `@Param()`, on a single property (`@Body('email', { schema: z.email() })`), and on custom decorators from `createParamDecorator()`.
|
||||
- Path and query values are strings: use `z.coerce.number()` for numbers.
|
||||
- By default the handler receives the schema's output (coerced, defaulted, transformed). `new StandardSchemaValidationPipe({ transform: false })` passes the input through instead.
|
||||
- Failures are 400 with `message` as an array of strings prefixed by the property path, e.g. `"title: Too small: expected string to have >=1 characters"`.
|
||||
- Unknown keys: `z.object()` strips them, `z.strictObject()` rejects them (`Unrecognized key: "age"`).
|
||||
- Booleans in query strings: `z.stringbool()` (`"true"`, `"1"`, `"yes"` → true; `"false"`, `"0"`, `"no"` → false; anything else is a 400). `z.coerce.boolean()` is JavaScript's `Boolean()`: any non-empty string, `"false"` included, is `true` (checked, Zod 4.6).
|
||||
- An empty PATCH body (`{}`) passes `.partial()`. If the contract requires at least one field, add `.refine((v) => Object.keys(v).length > 0, 'Nothing to update')`.
|
||||
- The same schemas describe the API in `@nestjs/swagger` (Zod 4.2+ converts itself): see the `nestjs-production` skill.
|
||||
|
||||
## class-validator DTOs
|
||||
|
||||
```typescript
|
||||
// main.ts
|
||||
app.useGlobalPipes(new ValidationPipe({ whitelist: true })); // add forbidNonWhitelisted: true to reject unknown keys
|
||||
```
|
||||
|
||||
```typescript
|
||||
import { PartialType } from '@nestjs/mapped-types';
|
||||
import { IsBoolean, IsString, Length, ValidateIf } from 'class-validator';
|
||||
|
||||
export class CreateNoteDto {
|
||||
@IsString()
|
||||
@Length(1, 200)
|
||||
title: string;
|
||||
}
|
||||
|
||||
export class UpdateNoteDto {
|
||||
// Not @IsOptional(): that skips every rule for null as well as undefined,
|
||||
// so {"title": null} would reach the database.
|
||||
@ValidateIf((_, value) => value !== undefined)
|
||||
@IsString()
|
||||
@Length(1, 200)
|
||||
title?: string;
|
||||
|
||||
@ValidateIf((_, value) => value !== undefined)
|
||||
@IsBoolean()
|
||||
archived?: boolean;
|
||||
}
|
||||
|
||||
// Or derive it: PartialType() applies @IsOptional() to every field (null gets through)
|
||||
// unless you pass skipNullProperties: false, which applies the ValidateIf above instead.
|
||||
export class UpdateNoteDto2 extends PartialType(CreateNoteDto, { skipNullProperties: false }) {}
|
||||
```
|
||||
|
||||
Checked on Nest 12.5 with class-validator 0.15: with `@IsOptional() @IsString()`, `{"title": null}` passes (200); with `@ValidateIf((_, v) => v !== undefined) @IsString()`, it's a 400, and `{}` still passes.
|
||||
|
||||
- Nested objects and arrays: `@ValidateNested()` and `@Type(() => Address)` (from class-transformer) together; `@ValidateNested({ each: true })` for arrays. Checked: with both, `{"address":{"city":5}}` is a 400 (`address.city must be a string`); without `@Type()`, it passes as 201.
|
||||
- `whitelist: true` drops unknown properties without a word, so a misspelt field (`tilte`) is silently ignored and the update does nothing. `forbidNonWhitelisted: true` answers 400 instead.
|
||||
- Without `transform: true`, `@Query('page') page: number` is still the string `"2"` at run time: TypeScript types don't convert anything.
|
||||
- `ValidationPipe({ transform: true })` turns the body into a DTO instance and converts primitive path/query params to their declared types.
|
||||
- Arrays of DTOs: `new ParseArrayPipe({ items: CreateNoteDto })`.
|
||||
Reference in New Issue
Block a user