Bỏ qua, tới nội dung chính

Kiến trúc · ADR 0002

API cross-cutting concerns: traceability, errors, validation

Trạng thái
accepted — points 2 and 3 superseded by ADR-0003
Ngày
2026-09-20
Người quyết định
Alex

Context

The NestJS app existed as a bootstrap with a health route. Before any feature module lands, the decisions that every later module inherits had to be fixed: how a request is traced, what an error looks like, where validation comes from, and how a route becomes private.

A working reference was available in a sibling project (VDCD_Backend, NestJS 11 + TypeORM). Its layout is good and was adopted: common/{decorators,filters,guards,interceptors}, config/, modules/*, plus helmet, cookie-parser, environment-aware CORS and a versioned global prefix.

Its implementations were not adopted, for four reasons: no request id anywhere, any in the filter and the response interceptor (this repo runs strict + noUncheckedIndexedAccess), a bespoke error shape, and a TransformInterceptor that wraps every response in {statusCode, data} — which fights OpenAPI typing and wraps errors too.

Decision

  1. Request id via AsyncLocalStorage. RequestContextMiddleware runs first, honours an inbound x-request-id (shape-checked) or mints one, echoes it on the response, and opens the context. The filter, the logging interceptor, the JWT strategy and any queued job read from there. One id follows a request through API → queue → worker.
  2. RFC 7807 Problem Details as the only error shape, served as application/problem+json, carrying requestId. Defined once in packages/shared, so the web client parses the same type the API produces. 4xx log at debug, 5xx log with the stack, and stacks never cross the wire in production.
  3. No response envelope. Superseded by ADR-0003: every response is enveloped.
  4. Zod as the only validator, via nestjs-zod: DTOs are createZodDto(sharedSchema), so one definition validates the request, types the handler and generates the OpenAPI schema. This requires zod v4 — nestjs-zod@5 cannot infer through zod 3's parse signature, which silently degrades every DTO to unknown. The workspace was moved to zod 4 for this.
  5. Private by default. JwtAuthGuard is global; a route opts out with @Public(). Forgetting a guard can only fail closed. RolesGuard is global too and typed against the shared Role union. Ownership checks are a separate per-module guard — role alone never answers "is this the instructor who owns this course?".
  6. Env validated at boot with Zod. Missing or weak values stop the process; messages name the variable and the reason, never the value.
  7. Prisma pinned to the v6 line. prisma@latest currently resolves to 8.0.0-rc, whose CLI is a different product — prisma generate does not exist in it. Every tutorial the team will find describes v6. Pinned deliberately, not accidentally.
  8. Refresh tokens are opaque, hashed and rotated. Stored as SHA-256 so a database dump is not a set of live sessions; presenting a revoked token revokes the whole chain for that user.

Alternatives considered

  • class-validator DTOs (NestJS default, already installed). Rejected: it duplicates every shape that packages/shared already defines, and the two drift.
  • nestjs-pino for logging. Deferred. The Logger + interceptor pair covers the need today and adds no transport to configure; pino goes in when logs need shipping somewhere.
  • Keeping tsx as the worker runtime. Rejected: it forces TypeScript into the production image. packages/shared now builds to dual ESM/CJS via tsup, so the worker runs node dist/main.js.

Consequences

  • Easy: every new module inherits tracing, error shape, auth and validation for free.
  • Constrained: @typescript-eslint/consistent-type-imports is off inside apps/api. NestJS resolves constructor dependencies from emitDecoratorMetadata; rewriting those imports to import type erases the class at runtime and the container fails to inject it — code that compiles and then crashes on boot. The rule stays on everywhere else.
  • packages/shared now has a build step. Turbo's dependsOn: ["^build"] orders it; consumers resolve through its exports map rather than raw source.
  • Owed: .js specifiers belong in the worker's own relative imports (it is ESM on NodeNext) and must not appear inside packages/shared — Turbopack cannot map those back to .ts, which breaks the web build.