backend
nestjsnodejstypescriptapidecorators
nestjs
Build Node.js server-side applications with NestJS: modules, dependency injection, decorators, and API layers.
Models: sonnetopusgpt-6gemini-3glm-5
NestJS
Progressive Node.js framework with TypeScript, decorators, and DI.
Quick Start
npm i -g @nestjs/cli && nest new my-api
cd my-api && npm run start:devCore Concepts
Modules
@Module({ imports: [UsersModule], controllers: [AppController], providers: [AppService] })
export class AppModule {}Controllers
@Controller('users')
export class UsersController {
@Get() findAll() { return this.usersService.findAll() }
@Post() @Body() create(dto: CreateUserDto) { return this.usersService.create(dto) }
}Providers (Services)
@Injectable()
export class UsersService {
private users: User[] = []
findAll() { return this.users }
create(dto: CreateUserDto) { const user = { id: Date.now(), ...dto }; this.users.push(user); return user }
}When to Use
- Structured TypeScript APIs
- Microservices with NATS/RabbitMQ
- GraphQL + REST hybrid APIs
- Projects needing strong structure
Step-by-Step
1. Init: `nest new project`
2. Generate: `nest g module users`, `nest g controller users`, `nest g service users`
3. Define entities and DTOs
4. Run: `npm run start:dev`
Examples
// Full module wired with DI: controller + provider + repository
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
import { User } from './user.entity';
@Module({
imports: [TypeOrmModule.forFeature([User])],
controllers: [UsersController],
providers: [UsersService],
exports: [UsersService],
})
export class UsersModule {}
// Validation DTO with class-validator
import { IsEmail, IsString, MinLength } from 'class-validator';
export class CreateUserDto {
@IsEmail() email!: string;
@IsString() @MinLength(2) name!: string;
}# Generate a module with CRUD scaffold, then hit the endpoint
nest g resource users --no-spec
curl http://localhost:3000/users
curl -X POST http://localhost:3000/users -H "content-type: application/json" -d '{"email":"a@b.c","name":"Alice"}'Best Practices
- Organize by feature modules with clear providers and controllers.
- Use DTOs and ValidationPipe for typed request/response contracts.
- Inject services via constructor DI; keep controllers thin.
- Use interceptors for logging, guards for auth, and filters for errors.
- Prefer async handlers and non-blocking database access.
- Write e2e tests with supertest against the full Nest app.
Troubleshooting
- DI errors: verify providers are registered in the right module.
- Validation not firing: ensure ValidationPipe is applied globally.
- Circular imports: use forwardRef() and split the module.
- Slow handlers: move heavy work to a queue or cache results.
Validation
1. Server starts on port 3000
2. CRUD endpoints respond correctly
3. Dependency injection resolves providers
NestJS
Прогрессивный Node.js фреймворк: TypeScript, декораторы и DI.
Быстрый старт
npm i -g @nestjs/cli && nest new my-api
cd my-api && npm run start:devОсновные концепции
Модули
@Module({ imports: [UsersModule], controllers: [AppController], providers: [AppService] })
export class AppModule {}Контроллеры
@Controller('users')
export class UsersController {
@Get() findAll() { return this.usersService.findAll() }
@Post() @Body() create(dto: CreateUserDto) { return this.usersService.create(dto) }
}Провайдеры (Сервисы)
@Injectable()
export class UsersService {
private users: User[] = []
findAll() { return this.users }
create(dto: CreateUserDto) { const user = { id: Date.now(), ...dto }; this.users.push(user); return user }
}Когда использовать
- Структурированные TypeScript API
- Микросервисы на NATS/RabbitMQ
- Гибрид GraphQL + REST
- Проекты, требующие строгой структуры
Пошаговое руководство
1. Инициализация: `nest new project`
2. Генерация: `nest g module users`, `nest g controller users`, `nest g service users`
3. Определите сущности и DTO
4. Запуск: `npm run start:dev`
Примеры
// Полный модуль с DI: контроллер + провайдер + репозиторий
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
import { User } from './user.entity';
@Module({
imports: [TypeOrmModule.forFeature([User])],
controllers: [UsersController],
providers: [UsersService],
exports: [UsersService],
})
export class UsersModule {}
// Validation DTO с class-validator
import { IsEmail, IsString, MinLength } from 'class-validator';
export class CreateUserDto {
@IsEmail() email!: string;
@IsString() @MinLength(2) name!: string;
}# Генерация модуля с CRUD-скаффолдом, затем запрос к endpoint
nest g resource users --no-spec
curl http://localhost:3000/users
curl -X POST http://localhost:3000/users -H "content-type: application/json" -d '{"email":"a@b.c","name":"Alice"}'Лучшие практики
- Организуйте по фичам-модулям с ясными providers и controllers.
- DTO и ValidationPipe для типизированных контрактов.
- Сервисы через конструкторный DI; контроллеры тонкие.
- Interceptors для логов, guards для auth, filters для ошибок.
- Async-обработчики и неблокирующий доступ к БД.
- e2e-тесты с supertest против полного Nest-приложения.
Устранение неполадок
- Ошибки DI: проверьте регистрацию providers в нужном модуле.
- Валидация не срабатывает: глобально примените ValidationPipe.
- Циклические импорты: forwardRef() и разбиение модуля.
- Медленные обработчики: очередь или кэш результатов.
Валидация
1. Сервер стартует на порту 3000
2. CRUD-эндпоинты отвечают корректно
3. Инъекция зависимостей резолвит провайдеров