Critical Patterns
Module Organization (REQUIRED)
// ✅ ALWAYS: Feature modules with clear boundaries @Module({ imports: [TypeOrmModule.forFeature([User])], controllers: [UsersController], providers: [UsersService], exports: [UsersService], }) export class UsersModule {}
DTOs with Validation (REQUIRED)
// ✅ ALWAYS: Use class-validator decorators export class CreateUserDto { @IsString() @MinLength(2) name: string;
@IsEmail() email: string;
@IsString() @MinLength(8) password: string; }
Exception Filters (REQUIRED)
// ✅ ALWAYS: Custom exceptions for domain errors
export class UserNotFoundException extends NotFoundException {
constructor(userId: string) {
super(User with ID ${userId} not found);
}
}
// Global exception filter @Catch() export class AllExceptionsFilter implements ExceptionFilter { catch(exception: unknown, host: ArgumentsHost) { // Handle all exceptions } }
Decision Tree
Need CRUD? → Use @nestjs/crud Need auth? → Use @nestjs/passport + JWT Need caching? → Use @nestjs/cache-manager Need queue processing? → Use @nestjs/bull Need GraphQL? → Use @nestjs/graphql Need WebSockets? → Use @nestjs/websockets
Code Examples
Controller with Guards
@Controller('users') @UseGuards(JwtAuthGuard) export class UsersController { constructor(private readonly usersService: UsersService) {}
@Get(':id') async findOne(@Param('id') id: string): Promise<User> { return this.usersService.findById(id); }
@Post() @UsePipes(new ValidationPipe({ transform: true })) async create(@Body() dto: CreateUserDto): Promise<User> { return this.usersService.create(dto); } }
Service with Repository
@Injectable() export class UsersService { constructor( @InjectRepository(User) private usersRepository: Repository<User>, ) {}
async findById(id: string): Promise<User> { const user = await this.usersRepository.findOne({ where: { id } }); if (!user) throw new UserNotFoundException(id); return user; } }
Commands
nest new myapp nest generate module users nest generate controller users nest generate service users npm run start:dev npm run test
Resources
- Backend patterns: backend.md