Skip to content

项目架构全览

NestJS 生产级后端基线模板 v0.7.1。

1. 技术栈

层级技术版本
运行时Node.js≥22.0.0
语言TypeScript(strict, ESM, nodenext)5.9.3
框架NestJS11.1.17
ORMPrisma + @prisma/adapter-pg7.5.0
数据库PostgreSQL≥18
认证JWT ES256 + bcryptjs(10 rounds)
验证Zod 4 + nestjs-zod4.3.6
日志Pino + nestjs-pino10.3.1
安全Helmet + @nestjs/throttler + CORS
测试Jest 30 + Supertest30.3.0
容器Docker 多阶段(node:22-slim)
包管理pnpm≥8.0.0

2. 系统分层结构

mermaid
flowchart TD
    Client(["HTTP Client"])

    subgraph EL["Express 层"]
        direction LR
        H["Helmet"] --> Comp["Compression ≥1KB"] --> CP["CookieParser"]
    end

    subgraph CM["自定义中间件(顺序执行)"]
        direction LR
        RP["① RequestPreprocessing\nULID req.id + version"] --> RS["② RequestScope\nAsyncLocalStorage"] --> CORS["③ CORS Whitelist"]
    end

    subgraph GD["全局守卫"]
        direction LR
        TG["ThrottlerGuard\n3 级限流"] --> AG["AuthGuard\nJWT ES256"]
    end

    ZVP["ZodValidationPipe(全局)"]

    subgraph BL["业务层"]
        direction LR
        AC["AppController\n/health /test/*"] --- ATC["AuthController\n/auth/*"] --- EC["ExceptionCatalogController\n/errors"]
    end

    subgraph SL["Service 层"]
        direction LR
        AS["AppService"] --- AUS["AuthService + TokenService"] --- RCS["AlsService"]
    end

    subgraph IL["Infrastructure 层"]
        direction LR
        DB["DatabaseService\nPrisma + PG Adapter"] --- ST["StorageService(预留)"]
    end

    subgraph GW["全局包装(拦截器 + 过滤器)"]
        direction LR
        PI["PerformanceInterceptor"] --- RFI["ResponseFormatInterceptor"] --- TI["TimeoutInterceptor 30s"] --- ZSI["ZodSerializerInterceptor"]
        AEF["AllExceptionsFilter"]
    end

    Client --> EL --> CM --> GD --> ZVP --> BL --> SL --> IL
    GW -.包裹业务层.-> BL
    AEF -.兜底捕获.-> BL

3. 模块职责

模块路径职责
Appsrc/app.*全局中间件、拦截器、过滤器装配;健康检查
Authsrc/modules/auth/注册/登录/刷新令牌;JWT 签发与验证
ExceptionCatalogsrc/modules/exception-catalog/GET /errors:错误码自文档化 API
Commonsrc/common/工具函数库、装饰器、AppException / ClientException / SystemException 异常基类体系
Constantssrc/constants/所有常量的唯一定义来源
Infrasrc/infra/DatabaseService(Prisma + PG)、存储抽象

4. 子文档导航

文档核心问题
request-pipeline.mdHTTP 请求经历哪些阶段?各阶段详细逻辑?
exception-system.md异常系统如何设计?
auth-module.md双令牌策略如何工作?JWT 如何签发与验证?
database.md连接池如何配置?查询如何监控与脱敏?
observability.md日志、追踪、告警如何串联?
cicd-deployment.md代码如何从提交走到生产容器?

5. 关键设计决策摘要

下列决策对架构有全局影响:

决策选择核心理由
认证算法JWT ES256(EC 非对称)公钥可分发,支持密钥分离;EC 密钥更短,性能优于 RSA;HS256 无法安全分发验证密钥
主键类型ULID时间有序(优于 UUID v4),适合数据库索引
日志库Pino性能最优,原生 JSON,nestjs-pino 官方集成
请求上下文AsyncLocalStorage无需手动传参,任意层级可访问请求 ID
验证库Zod 4TypeScript-first,运行时验证与类型推断统一