jvinhit//lab

Search posts

Type to search across journal entries.

navigate open esc close

Series · 20 phần

NestJS Zero to Hero — Modern TypeScript Back-end Development

Lộ trình tiếng Việt 20 phần biến một project TaskFlow từ HTTP API đầu tiên thành back-end production bằng NestJS 11 và TypeScript strict. Chặng nền tảng giải thích controller, provider, dependency injection, module graph, request lifecycle, config và logging bằng mental model có thể debug. Chặng REST và data thiết kế contract, validation, OpenAPI, PostgreSQL, Prisma, transaction, concurrency, idempotency cùng kiến trúc ports-and-adapters. Chặng chất lượng hoàn thiện authentication, refresh-token rotation, authorization theo policy và tenant, security baseline, testing nhiều tầng, profiling, Fastify, cache và rate limit. Chặng cuối thêm BullMQ, outbox, WebSocket/SSE, GraphQL, microservices/gRPC, OpenTelemetry, health check, graceful shutdown, Docker và CI/CD. Mỗi bài có lab tiếp nối, lệnh chạy, test, failure mode, bài tập và acceptance criteria; capstone cuối series tạo trải nghiệm triển khai một hệ thống NestJS hoàn chỉnh thay vì chỉ học decorator rời rạc.

01 Nền tảng NestJS và runtime

Tạo TaskFlow API, hiểu controller, provider, DI, module graph, request pipeline, configuration và bootstrap có kiểm soát.

  1. Hiểu NestJS giải quyết bài toán gì, dựng TaskFlow API bằng NestJS 11 và TypeScript strict, rồi lần theo một request từ bootstrap tới controller.

  2. Thiết kế controller mỏng, route REST có chủ đích, status/header/query/param đúng ngữ nghĩa và xây Tasks API in-memory có thể kiểm thử bằng curl.

  3. Làm chủ provider token, custom provider, useClass/useValue/useFactory/useExisting, scope và cách thiết kế dependency có thể thay thế, kiểm thử.

  4. Dùng module như public API của capability, kiểm soát provider visibility, tránh global/circular dependency và tạo dynamic module cấu hình rõ ràng.

  5. Lần theo middleware, guard, interceptor, pipe, controller và exception filter; đặt auth, validation, logging và error mapping đúng tầng.

  6. Validate environment lúc startup, chia config theo namespace, bảo vệ secret, chuẩn hóa structured logging và biến main.ts thành bootstrap có thể kiểm thử.

02 REST, dữ liệu và kiến trúc

Thiết kế HTTP contract, kết nối PostgreSQL/Prisma, xử lý transaction và đưa business rule vào boundary có thể test.

  1. Thiết kế API contract có runtime validation, response serialization, pagination, versioning, stable error và OpenAPI để client có thể tích hợp an toàn.

  2. Kết nối PostgreSQL bằng Prisma 7 driver adapter, quản lý schema/migration/client lifecycle và implement repository mà không để ORM rò vào domain.

  3. Thiết kế transaction boundary, optimistic concurrency, idempotency key và retry an toàn để TaskFlow đúng khi nhiều request chạy đồng thời.

  4. Đưa business rule ra khỏi Nest/Prisma, thiết kế domain model và application use case, map adapter ở composition root, giữ modular monolith dễ test.

03 Bảo mật, chất lượng và hiệu năng

Xây authentication/authorization đúng nghĩa, khóa hành vi bằng test và đo trước khi tối ưu cache hoặc adapter.

  1. Xây password login an toàn, access JWT có issuer/audience, global Passport guard, refresh session rotation/reuse detection và logout/revoke có state.

  2. Thiết kế permission/policy/resource authorization, tenant isolation, chống IDOR và cấu hình Helmet, CORS, CSRF, rate limit, audit log đúng threat model.

  3. Xây testing pyramid cho domain/use case/module/Prisma/HTTP, dùng Nest TestingModule, Supertest và Testcontainers, giữ test deterministic và cô lập.

  4. Đo p95/p99, event loop, query và memory; thử Fastify đúng cách, thiết kế cache tenant-aware/invalidation và bảo vệ hệ thống khỏi overload.

04 Async, phân tán và production

Thêm queue, realtime, GraphQL, messaging/gRPC, observability, graceful shutdown và delivery pipeline cho capstone.

  1. Đưa tác vụ chậm sang BullMQ/Redis, thiết kế retry/backoff/dead letter, xử lý job idempotent và nối PostgreSQL transaction với queue qua outbox.

  2. Chọn SSE hay WebSocket, xác thực connection, authorize room theo tenant, xử lý reconnect/replay/backpressure và broadcast qua nhiều Nest replica.

  3. Thêm GraphQL adapter lên cùng use case, thiết kế schema/pagination/error/auth, giải N+1 bằng DataLoader và giới hạn depth/complexity/operation.

  4. Tách Notification service có lý do, dùng RabbitMQ event at-least-once và gRPC nội bộ có deadline, version contract, idempotency, tracing và ownership dữ liệu.

  5. Instrument traces/metrics/logs bằng OpenTelemetry, thiết kế low-cardinality RED metrics, liveness/readiness và shutdown drain HTTP/DB/queue an toàn.

  6. Đóng gói NestJS thành image tối thiểu, chạy migration/release an toàn, dựng CI/CD quality gates, rollout/rollback và hoàn thiện TaskFlow portfolio capstone.