← 返回
开发者工具
中文
NestJS
Avoid common NestJS mistakes — DI scoping, circular dependencies, validation pipes, and module organization traps.
避免常见的 NestJS 错误——依赖注入作用域、循环依赖、验证管道和模块组织陷阱。
ivangdavila
开发者工具
clawhub
v1.0.0 1 版本 99866.9 Key: 无需
#latest
概述
Dependency Injection
- Provider not available — must be in
providers array AND exports if used by other modules - Circular dependency crashes — use
forwardRef(() => Module) in both modules - Default scope is singleton — same instance across requests, careful with state
- Request-scoped provider —
@Injectable({ scope: Scope.REQUEST }), propagates to dependents
Module Organization
- Import module, not provider directly —
imports: [UserModule] not providers: [UserService] exports makes providers available to importers — without it, provider stays private- Global modules need
@Global() decorator — only for truly shared (config, logger) forRoot() vs forRootAsync() — async for when config depends on other providers
Validation
ValidationPipe needs class-validator decorators — plain classes won't validate- Enable
transform: true for auto-transformation — string "1" to number 1 whitelist: true strips unknown properties — forbidNonWhitelisted: true to error instead- Nested objects need
@ValidateNested() AND @Type(() => NestedDto) — both required
Execution Order
- Middleware → Guards → Interceptors (pre) → Pipes → Handler → Interceptors (post) → Filters
- Guards can't access transformed body — run before pipes
- Global pipes run before route pipes — but after guards
- Exception filters catch errors from entire chain — including guards and pipes
Exception Handling
throw new HttpException() not return — must throw for filter to catch- Custom exceptions extend
HttpException — or implement ExceptionFilter - Unhandled exceptions become 500 — wrap external calls in try/catch
- Built-in exceptions:
BadRequestException, NotFoundException, etc. — use these, not generic HttpException
Testing
createTestingModule doesn't auto-mock — provide mocks explicitly in providers- Override with
.overrideProvider(X).useValue(mock) — before .compile() - E2E tests need
app.init() — and app.close() in afterAll - Request-scoped providers complicate unit tests — consider making them singleton when possible
Common Mistakes
@Body() without DTO returns plain object — no validation, no transformation@Param('id') is always string — use ParseIntPipe for number: @Param('id', ParseIntPipe)- Guards returning false gives 403 — throw specific exception for better error messages
- Async providers need factory —
useFactory: async () => await createConnection() - Forgetting
await on async service methods — returns Promise, not value
版本历史
共 1 个版本
-
v1.0.0
当前
2026-03-29 01:35 安全 安全
安全检测
腾讯云安全 (Sanbu)
安全,无风险
查看报告
🔗 相关推荐
developer-tools
larsonreever
AI驱动平台,提供快速全栈开发、智能体、工作流自动化及低代码AI集成的可扩展产品创建。
★ 68
📥 180,601
ai-intelligence
ivangdavila
自我反思+自我批评+自我学习+自组织记忆。智能体评估自身工作、发现错误并持续改进。
★ 1,364
📥 319,297
developer-tools
steipete
Google Workspace 命令行工具,支持 Gmail、日历、云端硬盘、通讯录、表格和文档。
★ 921
📥 185,964