| name | nestjs-patterns |
| description | NestJS 架构模式,涵盖模块、控制器、提供者、DTO 验证、守卫、拦截器、配置以及生产级 TypeScript 后端。 |
| origin | ecc |
NestJS 开发模式
适用于模块化 TypeScript 后端的生产级 NestJS 模式。
何时启用
- 构建 NestJS API 或服务时
- 组织模块、控制器和提供者时
- 添加 DTO 验证、守卫、拦截器或异常过滤器时
- 配置环境感知设置和数据库集成时
- 测试 NestJS 单元或 HTTP 端点时
项目结构
src/
├── app.module.ts
├── main.ts
├── common/
│ ├── filters/
│ ├── guards/
│ ├── interceptors/
│ └── pipes/
├── config/
│ ├── configuration.ts
│ └── validation.ts
├── modules/
│ ├── auth/
│ │ ├── auth.controller.ts
│ │ ├── auth.module.ts
│ │ ├── auth.service.ts
│ │ ├── dto/
│ │ ├── guards/
│ │ └── strategies/
│ └── users/
│ ├── dto/
│ ├── entities/
│ ├── users.controller.ts
│ ├── users.module.ts
│ └── users.service.ts
└── prisma/ or database/
- 将领域代码保留在功能模块内。
- 将跨切面的过滤器、装饰器、守卫和拦截器放在
common/ 中。
- 将 DTO 保留在所属模块附近。
启动与全局验证
async function bootstrap() {
const app = await NestFactory.create(AppModule, { bufferLogs: true });
app.useGlobalPipes(
({
: ,
: ,
: ,
: { : },
}),
);
app.( (app.()));
app.( ());
app.(process.. ?? );
}
();