No slash command · from nestjs-plugin
Guides NestJS module structure, dependency injection, lifecycle hooks, configuration, exception handling, and logging conventions. Use when implementing or modifying NestJS backend code.
Ships in nestjs-plugin. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
This skill encodes module-level idioms for NestJS backend code. Apply alongside decorator-patterns (decorator-specific syntax) and js-foundation:typescript-patterns (general TS strictness).
Standalone application:
project-root/
├── nest-cli.json
├── package.json
├── tsconfig.json
├── tsconfig.build.json
├── src/
│ ├── main.ts # bootstrap
│ ├── app.module.ts # root module
│ ├── app.controller.ts # optional, often just /healthz
│ ├── app.service.ts # optional
│ ├── config/ # config files (app.config.ts, db.config.ts)
│ ├── common/ # shared (filters, interceptors, pipes, decorators)
│ │ ├── filters/
│ │ ├── interceptors/
│ │ ├── pipes/
│ │ └── decorators/
│ ├── users/ # feature module
│ │ ├── users.module.ts
│ │ ├── users.controller.ts
│ │ ├── users.service.ts
│ │ ├── dto/
│ │ │ ├── create-user.dto.ts
│ │ │ └── update-user.dto.ts
│ │ ├── entities/
│ │ │ └── user.entity.ts
│ │ └── tests/ # often co-located OR in /test
│ ├── auth/
│ └── ...
├── test/ # e2e tests
│ └── *.e2e-spec.ts
└── dist/ # build output, gitignored
Monorepo (Nx-flavored, nest-cli.json "monorepo": true):
project-root/
├── nest-cli.json
├── apps/
│ └── api/
│ └── src/
└── libs/
├── shared/
└── users/
Mirror what exists. Don't introduce a new layout pattern for one feature.
One feature = one module:
// src/users/users.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
import { User } from './entities/user.entity';
@Module({
imports: [TypeOrmModule.forFeature([User])],
controllers: [UsersController],
providers: [UsersService],
exports: [UsersService], // export only what other modules need
})
export class UsersModule {}
Wire into root:
// src/app.module.ts
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
TypeOrmModule.forRootAsync({...}),
UsersModule,
AuthModule,
],
})
export class AppModule {}
@Global() sparingly@Global()
@Module({
providers: [LoggerService],
exports: [LoggerService],
})
export class LoggerModule {}
Use only for genuinely cross-cutting deps (logger, config, DB connection). For two unrelated features needing the same service — explicit import is clearer.
If UsersModule and OrdersModule import each other:
shared/ lib.forwardRef(() => OtherModule) with a comment explaining the dependency cycle.imports: [forwardRef(() => OrdersModule)]
// circular: User has many Orders; Order belongs to User. Type-only import in service.
@Injectable()
export class UsersService {
constructor(
private readonly users: Repository<User>,
private readonly mailer: MailerService,
@Inject('AUDIT_LOG') private readonly audit: AuditLog,
) {}
}
private readonly — DI props don't get reassigned.@Inject('TOKEN').@Module({
providers: [
UsersService,
{
provide: 'AUDIT_LOG',
useClass: ProductionAuditLog,
},
{
provide: 'CONFIG_OPTIONS',
useFactory: (config: ConfigService) => ({
retries: config.get<number>('RETRIES', 3),
}),
inject: [ConfigService],
},
{
provide: APP_GUARD,
useClass: JwtAuthGuard,
},
],
})
useClass — bind interface to implementation.useValue — static value (constants, configs).useFactory — runtime computation; declare inject for factory deps.useExisting — alias another provider.@Injectable({ scope: Scope.DEFAULT }) // singleton (implicit default)
@Injectable({ scope: Scope.REQUEST }) // per-request — propagates UP the dep chain
@Injectable({ scope: Scope.TRANSIENT }) // new instance per inject
Scope.REQUEST is contagious — anything injecting a request-scoped provider becomes request-scoped too. Use only when you genuinely need per-request state (e.g., request-bound logger context). Costly otherwise.
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
validationSchema: Joi.object({
NODE_ENV: Joi.string().valid('development', 'test', 'production').required(),
PORT: Joi.number().port().default(3000),
DATABASE_URL: Joi.string().uri().required(),
}),
validationOptions: { abortEarly: false },
}),
],
})
If validationSchema fails on boot, the app crashes loud — exactly what you want.
@Injectable()
export class DatabaseService {
constructor(private readonly config: ConfigService) {
const url = this.config.get<string>('DATABASE_URL', { infer: true });
}
}
infer: true — TypeScript infers return type from schema if you typed it.config.get('CACHE_TTL', 60).process.env.X outside config/ setup files.// src/config/database.config.ts
import { registerAs } from '@nestjs/config';
export default registerAs('database', () => ({
host: process.env.DB_HOST,
port: parseInt(process.env.DB_PORT ?? '5432', 10),
url: process.env.DATABASE_URL,
}));
// inject in feature
@Injectable()
class DbModuleOptions {
constructor(@Inject(databaseConfig.KEY) private cfg: ConfigType<typeof databaseConfig>) {}
}
// src/main.ts
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe({
whitelist: true, // strip unknown fields
forbidNonWhitelisted: true, // reject requests with unknown fields
transform: true, // class-transformer auto-cast
transformOptions: { enableImplicitConversion: true },
}));
await app.listen(3000);
}
bootstrap();
Without whitelist + forbidNonWhitelisted, extra payload fields silently pass through — that's a real source of mass-assignment bugs.
throw new BadRequestException('email already in use');
throw new UnauthorizedException(); // 401
throw new ForbiddenException('insufficient role'); // 403
throw new NotFoundException(`user ${id} not found`); // 404
throw new ConflictException('version mismatch'); // 409
throw new UnprocessableEntityException(...); // 422
throw new InternalServerErrorException(); // 500 (last resort)
For non-HTTP layers (microservice handlers, WebSocket gateways), throw plain Error subclasses; map at the boundary via filters or transports' built-in error handling.
@Catch(MyDomainException)
export class MyDomainExceptionFilter implements ExceptionFilter {
catch(exception: MyDomainException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
response.status(exception.statusCode).json({
error: exception.code,
message: exception.message,
});
}
}
Apply via @UseFilters(MyDomainExceptionFilter) per controller/route, or globally:
app.useGlobalFilters(new MyDomainExceptionFilter());
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
private readonly logger = new Logger(AllExceptionsFilter.name);
catch(exception: unknown, host: ArgumentsHost) {
this.logger.error('unhandled', exception);
// re-throw or format default response
}
}
Add LAST in useGlobalFilters order (innermost catch-all).
@Injectable()
export class WarmupService implements OnModuleInit, OnApplicationShutdown {
async onModuleInit() {
// run after this module's providers instantiated
await this.warmCache();
}
async onApplicationShutdown(signal?: string) {
// close DB pool, drain queues
this.logger.log(`shutting down: ${signal}`);
await this.cleanup();
}
}
Enable shutdown hooks in main:
const app = await NestFactory.create(AppModule);
app.enableShutdownHooks();
Order:
OnModuleInit — after module's deps ready, before app boots.OnApplicationBootstrap — after ALL modules ready.OnModuleDestroy / OnApplicationShutdown — graceful shutdown on SIGTERM/SIGINT.Built-in Logger:
@Injectable()
export class UsersService {
private readonly logger = new Logger(UsersService.name);
async create(dto: CreateUserDto) {
this.logger.log(`creating user ${dto.email}`);
try {
// ...
} catch (err) {
this.logger.error('create failed', err);
throw err;
}
}
}
For structured production logs, swap globally:
// option A: nestjs-pino
const app = await NestFactory.create(AppModule, { bufferLogs: true });
app.useLogger(app.get(Logger));
// option B: custom logger implementing LoggerService
app.useLogger(new MyStructuredLogger());
new MyService() outside test files — always inject.process.env.X in business code — use ConfigService.try/catch swallowing errors silently.this.someInjectedService.field = newValue).@Global() on every shared module — defeats explicit-imports clarity.forwardRef to "fix" a real coupling problem.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
5 skills in this plugin
/decorator-patternsNestJS decorator usage: built-in route/param/class decorators, custom decorators via `createParamDecorator` and `SetMetadata`, metadata reflection via `Reflector`. Apply when designing controllers, guards, interceptors, or custom decorators.
Use this skill to:
- Pick the right built-in decorator for routes, params, and DI.
- Compose decorators (`@UseGuards(A, B) @UseInterceptors(C)`).
- Build custom param decorators (e.g., `@CurrentUser()`).
- Use metadata for role-based logic (Reflector + SetMetadata).
- Avoid common decorator mistakes.
Do NOT use this skill for:
- General module/DI patterns (see nest-conventions).
- GraphQL-specific decorators (see nest-advanced).
- ORM entity decorators (see nest-data-layer).
/nest-advancedGraphQL, WebSockets, and microservices patterns for NestJS. Apply only when the relevant package is in dependencies (`@nestjs/graphql`, `@nestjs/websockets`, `@nestjs/microservices`). Each section is orientation, not exhaustive — defer to NestJS docs for deep dives.
Use this skill to:
- Wire a GraphQL resolver (code-first) with class-validator inputs.
- Build a WebSocket gateway with auth and room management.
- Set up a microservice transport (TCP/RabbitMQ/NATS/Redis/Kafka) and message handlers.
Do NOT use this skill for:
- REST controllers (see nest-conventions + decorator-patterns).
- ORM (see nest-data-layer).
- Auth strategies (see security-analyst phase guidance).
/nest-data-layerORM patterns for NestJS: TypeORM, Prisma, Mongoose. Covers entities, repositories, transactions, migrations, common pitfalls (N+1, cascade deletes, transaction boundaries).
Use this skill to:
- Detect which ORM the project uses and apply matching patterns.
- Define entities/schemas with the right decorators.
- Inject repositories or Prisma client correctly.
- Run transactions at the service boundary.
- Write migrations that round-trip cleanly.
Do NOT use this skill for:
- Module/DI patterns (see nest-conventions).
- Decorator usage broadly (see decorator-patterns).
- Non-ORM raw SQL (rare; flag in BLOCKERS if needed).
/nest-testingNestJS testing patterns: Test.createTestingModule for unit/integration, mocking providers, e2e tests with INestApplication + supertest, ORM mocking (TypeORM/Prisma/Mongoose), test fixtures.
Use this skill to:
- Write unit tests for services with mocked dependencies.
- Write integration tests with real DI but mocked external services.
- Write e2e tests for HTTP endpoints via supertest.
- Mock repositories/Prisma client correctly.
- Cover services and controllers to ≥80%.
Do NOT use this skill for:
- Test framework setup (Jest/Vitest config — usually already in place).
- Frontend tests.
- Load testing (out of QA scope).
npx claudepluginhub aratkruglik/claude-sdlc --plugin nestjs-pluginOther plugins' skills for the same job