nestjs-best-practices · ejirocodes — скилл для Claude Code: правила NestJS 11
Скилл с практиками NestJS 11 для приложений на TypeScript: подсказывает, как писать модули, контроллеры и сервисы, и ловит типичные ошибки при ревью.
npx skills add ejirocodes/agent-skills --skill nestjs-best-practices -a claude-codeЧто делает nestjs-best-practices
Скилл включается, когда вы пишете, проверяете или переписываете код NestJS: модули, контроллеры, провайдеры, внедрение зависимостей, @Injectable, @Controller, @Module, middleware, гарды, интерцепторы, пайпы, фильтры исключений, DTO, JWT-аутентификация, стратегии Passport, TypeORM, Prisma, Drizzle, GraphQL-резолверы, микросервисы на TCP, Redis, NATS и Kafka, тесты.
Внутри — справочные файлы по темам: архитектура ядра, жизненный цикл запроса, валидация и пайпы, аутентификация, работа с базой, тестирование, OpenAPI и GraphQL, микросервисы. Плюс разбор частых ошибок: забыли forwardRef() при циклических зависимостях, бросили обычную ошибку вместо HttpException, не поставили @Injectable(), включили глобальный ValidationPipe без whitelist: true, импортировали модуль вместо экспорта провайдера, не вызвали ConfigModule.forRoot() перед асинхронным конфигом, в юнит-тестах не подменили сервис через overrideProvider(), а в E2E не изолировали состояние базы.
Отдельный раздел — изменения NestJS 11: минимум Node.js 20, Express v5 с именованными вайлдкардами и опциональными параметрами в фигурных скобках, обновлённый адаптер Fastify v5, а также динамические модули, которые при одинаковом конфиге, импортированном несколько раз, дают разные экземпляры. Если проект ещё на Express v4 или Node.js ниже 20, часть советов придётся отложить до обновления.
Какие задачи решает
- разложить модуль на контроллер, сервис и провайдеры без лишних связей
- настроить глобальный
ValidationPipeсwhitelistиforbidNonWhitelisted - разорвать циклическую зависимость через
forwardRef() - подменить сервис в юнит-тесте через
overrideProvider() - перевести маршруты на Express v5 с именованными вайлдкардами
Примеры запросов агенту
- Напиши модуль
UsersModuleс контроллером и сервисом, экспортни провайдер для других модулей - Проверь мой контроллер: правильно ли расставлены пайпы и фильтры исключений
- Перепиши этот сервис под NestJS 11, учти изменения Express v5
Как установить nestjs-best-practices
1Через Skills CLI (Vercel)
npx skills add ejirocodes/agent-skills --skill nestjs-best-practices -a claude-code2Вручную: положить файлы
~/.claude/skills/nestjs-best-practices/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/nestjs-best-practices/
1Через Skills CLI (Vercel)
npx skills add ejirocodes/agent-skills --skill nestjs-best-practices -a codex2Вручную: положить файлы
.agents/skills/nestjs-best-practices/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add ejirocodes/agent-skills --skill nestjs-best-practices -a cursor2Вручную: положить файлы
.cursor/skills/nestjs-best-practices/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install ejirocodes/agent-skills nestjs-best-practices2Вручную: положить файлы
.github/skills/nestjs-best-practices/SKILL.md1Через Skills CLI (Vercel)
npx skills add ejirocodes/agent-skills --skill nestjs-best-practices -a gemini-cli2Командой платформы
gemini skills install https://github.com/ejirocodes/agent-skills --path nestjs/skills/nestjs-best-practicesВручную: положить файлы
.devin/skills/nestjs-best-practices/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add ejirocodes/agent-skills --skill nestjs-best-practices -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Вопросы о nestjs-best-practices
Как установить nestjs-best-practices в Claude Code?
Выполните npx skills add ejirocodes/agent-skills --skill nestjs-best-practices -a claude-code. Скилл окажется в ~/.claude/skills/nestjs-best-practices/SKILL.md.
Что делает nestjs-best-practices?
Даёт агенту справочник по NestJS 11: архитектура, жизненный цикл запроса, валидация, аутентификация, база, тесты, OpenAPI и GraphQL, микросервисы. Агент опирается на него при написании и ревью кода.
Какие версии Node.js и Express нужны для NestJS 11?
Минимум Node.js 20. В Express v5 вайлдкарды должны быть именованными, например *splat, а опциональные параметры записываются в фигурных скобках: /:file{.:ext}.
Исходный текст
SKILL.md · MIT
---
name: nestjs-best-practices
description: "NestJS 11+ best practices for enterprise Node.js applications with TypeScript. Use when writing, reviewing, or refactoring NestJS controllers, services, modules, or APIs. Triggers on: NestJS modules, controllers, providers, dependency injection, @Injectable, @Controller, @Module, middleware, guards, interceptors, pipes, exception filters, ValidationPipe, class-validator, class-transformer, DTOs, JWT authentication, Passport strategies, @nestjs/passport, TypeORM entities, Prisma client, Drizzle ORM, repository pattern, circular dependencies, forwardRef, @nestjs/swagger, OpenAPI decorators, GraphQL resolvers, @nestjs/graphql, microservices, TCP transport, Redis transport, NATS, Kafka, NestJS 11 breaking changes, Express v5 migration, custom decorators, ConfigService, @nestjs/config, health checks, or NestJS testing patterns."
license: MIT
metadata:
author: ejirocodes
version: '1.0.0'
---
# NestJS 11 Best Practices
## Quick Reference
| Topic | When to Use | Reference |
|-------|-------------|-----------|
| **Core Architecture** | Modules, Providers, DI, forwardRef, custom decorators | [core-architecture.md](references/core-architecture.md) |
| **Request Lifecycle** | Middleware, Guards, Interceptors, Pipes, Filters | [request-lifecycle.md](references/request-lifecycle.md) |
| **Validation & Pipes** | DTOs, class-validator, ValidationPipe, transforms | [validation-pipes.md](references/validation-pipes.md) |
| **Authentication** | JWT, Passport, Guards, Local/OAuth strategies, RBAC | [authentication.md](references/authentication.md) |
| **Database** | TypeORM, Prisma, Drizzle ORM, repository patterns | [database-integration.md](references/database-integration.md) |
| **Testing** | Unit tests, E2E tests, mocking providers | [testing.md](references/testing.md) |
| **OpenAPI & GraphQL** | Swagger decorators, resolvers, subscriptions | [openapi-graphql.md](references/openapi-graphql.md) |
| **Microservices** | TCP, Redis, NATS, Kafka patterns | [microservices.md](references/microservices.md) |
## Essential Patterns
### Module with Providers
```typescript
@Module({
imports: [DatabaseModule],
controllers: [UsersController],
providers: [UsersService],
exports: [UsersService], // Export for other modules
})
export class UsersModule {}
```
### Controller with Validation
```typescript
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@Post()
create(@Body() createUserDto: CreateUserDto) {
return this.usersService.create(createUserDto);
}
@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number) {
return this.usersService.findOne(id);
}
}
```
### DTO with Validation
```typescript
import { IsEmail, IsString, MinLength, IsOptional } from 'class-validator';
export class CreateUserDto {
@IsEmail()
email: string;
@IsString()
@MinLength(8)
password: string;
@IsOptional()
@IsString()
name?: string;
}
```
### Exception Filter
```typescript
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const status = exception.getStatus();
response.status(status).json({
statusCode: status,
message: exception.message,
timestamp: new Date().toISOString(),
});
}
}
```
### Guard with JWT
```typescript
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
canActivate(context: ExecutionContext) {
return super.canActivate(context);
}
}
```
## NestJS 11 Breaking Changes
- **Express v5**: Wildcards must be named (e.g., `*splat`), optional params use braces `/:file{.:ext}`
- **Node.js 20+**: Minimum required version
- **Fastify v5**: Updated adapter for Fastify users
- **Dynamic Modules**: Same module with identical config imported multiple times = separate instances
## Common Mistakes
1. **Not using `forwardRef()` for circular deps** - Causes "cannot resolve dependency" errors; wrap in `forwardRef(() => ModuleName)`
2. **Throwing plain errors instead of HttpException** - Loses status codes, breaks exception filters; use `throw new BadRequestException('message')`
3. **Missing `@Injectable()` decorator** - Provider won't be injectable; always decorate services
4. **Global ValidationPipe without `whitelist: true`** - Allows unexpected properties; set `whitelist: true, forbidNonWhitelisted: true`
5. **Importing modules instead of exporting providers** - Use `exports` array to share providers across modules
6. **Async config without `ConfigModule.forRoot()`** - ConfigService undefined; import ConfigModule in AppModule
7. **Testing without `overrideProvider()`** - Uses real services in unit tests; mock dependencies with `overrideProvider(Service).useValue(mock)`
8. **E2E tests sharing database state** - No isolation between tests; use transactions or truncate tables in beforeEach
© ejirocodes · MIT · ejirocodes/agent-skills
Похожие скиллы
Все скиллы по теме «Бэкенд и API» →Сначала — nestjs-best-practices от других авторов.