๐ค
NestJS
Avoid common NestJS mistakes โ DI scoping, circular dependencies, validation pipes, and module organization traps.
ๅฎๅ
จ้่ฟ
๐ฌPrompt
ๆ่ฝ่ฏดๆ
name: NestJS description: Avoid common NestJS mistakes โ DI scoping, circular dependencies, validation pipes, and module organization traps. metadata: {"clawdbot":{"emoji":"๐ฑ","requires":{"bins":["node"]},"os":["linux","darwin","win32"]}}
Dependency Injection
- Provider not available โ must be in
providersarray ANDexportsif 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]notproviders: [UserService] exportsmakes providers available to importers โ without it, provider stays private- Global modules need
@Global()decorator โ only for truly shared (config, logger) forRoot()vsforRootAsync()โ async for when config depends on other providers
Validation
ValidationPipeneedsclass-validatordecorators โ plain classes won't validate- Enable
transform: truefor auto-transformation โ string"1"to number1 whitelist: truestrips unknown properties โforbidNonWhitelisted: trueto 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()notreturnโ must throw for filter to catch- Custom exceptions extend
HttpExceptionโ or implementExceptionFilter - Unhandled exceptions become 500 โ wrap external calls in try/catch
- Built-in exceptions:
BadRequestException,NotFoundException, etc. โ use these, not generic HttpException
Testing
createTestingModuledoesn't auto-mock โ provide mocks explicitly inproviders- Override with
.overrideProvider(X).useValue(mock)โ before.compile() - E2E tests need
app.init()โ andapp.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 โ useParseIntPipefor 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
awaiton async service methods โ returns Promise, not value
ๅฆไฝไฝฟ็จใNestJSใ๏ผ
- ๆๅผๅฐ้พ่พAI๏ผWeb ๆ iOS App๏ผ
- ็นๅปไธๆนใ็ซๅณไฝฟ็จใๆ้ฎ๏ผๆๅจๅฏน่ฏๆกไธญ่พๅ ฅไปปๅกๆ่ฟฐ
- ๅฐ้พ่พAI ไผ่ชๅจๅน้ ๅนถ่ฐ็จใNestJSใๆ่ฝๅฎๆไปปๅก
- ็ปๆๅณๆถๅ็ฐ๏ผๆฏๆ็ปง็ปญๅฏน่ฏไผๅ