AGENT SKILL

nest-conventions

ACTIVATE when creating NestJS modules, controllers, services, guards, pipes, or configuring dependency injection. ACTIVATE for 'NestJS', '@Module', '@Controller', '@Injectable', 'guard', 'pipe', 'DI token'. Covers: module-per-bounded-context structure, thin controllers, ZodValidationPipe, guards for auth, exception filters, Symbol token-based DI for interfaces, constructor injection only. DO NOT use for: domain layer code (see nest-ddd-conventions), Zod schema design (see zod-conventions).

License 许可
MIT
最近更新
2026-10-13
Stars
★ 9
Forks
2

01 前言 Front Matter

name
nest-conventions
description
ACTIVATE when creating NestJS modules, controllers, services, guards, pipes, or configuring dependency injection. ACTIVATE for 'NestJS', '@Module', '@Controller', '@Injectable', 'guard', 'pipe', 'DI token'. Covers: module-per-bounded-context structure, thin controllers, ZodValidationPipe, guards for auth, exception filters, Symbol token-based DI for interfaces, constructor injection only. DO NOT use for: domain layer code (see nest-ddd-conventions), Zod schema design (see zod-conventions).

02 资源文件 1

03 SKILL.md 正文

NestJS Conventions

Module Structure

1 module = 1 bounded context. Each module encapsulates its own controllers, services, and providers.

// ✅ CORRECT - Self-contained module
@Module({
  imports: [SharedModule],
  controllers: [ReceiptController],
  providers: [
    ReceiptService,
    { provide: RECEIPT_REPOSITORY, useClass: DrizzleReceiptRepository },
  ],
  exports: [ReceiptService], // Only export what other modules need
})
export class ReceiptModule {}

File Naming

Type Pattern Example
Module *.module.ts receipt.module.ts
Controller *.controller.ts receipt.controller.ts
Service *.service.ts receipt.service.ts
Guard *.guard.ts auth.guard.ts
Pipe *.pipe.ts zod-validation.pipe.ts
Filter *.filter.ts http-exception.filter.ts
Interceptor *.interceptor.ts logging.interceptor.ts
Test *.spec.ts receipt.service.spec.ts

Thin Controllers

Controllers handle HTTP concerns only. Delegate all business logic to services.

// ❌ AVOID - Business logic in controller
@Controller('receipts')
export class ReceiptController {
  @Post()
  async create(@Body() dto: CreateReceiptDto) {
    const lease = await this.leaseRepo.findById(dto.leaseId);

    if (!lease) {
      throw new NotFoundException('Lease not found');
    }

    const amount = lease.monthlyRent;
    const receipt = { leaseId: dto.leaseId, amount, period: dto.period };
    return this.receiptRepo.save(receipt);
  }
}

// ✅ CORRECT - Controller delegates to service
@Controller('receipts')
export class ReceiptController {
  constructor(private readonly receiptService: ReceiptService) {}

  @Post()
  async create(@Body(ZodValidationPipe) dto: CreateReceiptDto) {
    return this.receiptService.generate(dto);
  }
}

Guards (Authentication / Authorization)

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    const token = request.headers.authorization?.replace('Bearer ', '');

    if (!token) {
      throw new UnauthorizedException();
    }

    // Validate token...
    return true;
  }
}

// Usage: at controller or route level
@UseGuards(AuthGuard)
@Controller('receipts')
export class ReceiptController { ... }

Pipes (Validation)

Use a ZodValidationPipe for DTO validation with Zod schemas:

@Injectable()
export class ZodValidationPipe implements PipeTransform {
  constructor(private readonly schema: ZodSchema) {}

  transform(value: unknown) {
    const result = this.schema.safeParse(value);

    if (!result.success) {
      throw new BadRequestException(result.error.flatten());
    }

    return result.data;
  }
}

// Usage
@Post()
async create(
  @Body(new ZodValidationPipe(CreateReceiptSchema)) dto: CreateReceiptDto,
) {
  return this.receiptService.generate(dto);
}

See also: zod-conventions for Zod schema patterns.

Exception Filters

Centralized error handling:

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const status = exception.getStatus();

    response.status(status).json({
      statusCode: status,
      message: exception.message,
      timestamp: new Date().toISOString(),
    });
  }
}

// Register globally in main.ts
app.useGlobalFilters(new HttpExceptionFilter());

Dependency Injection

Token-based injection for interfaces

// Define token
export const RECEIPT_REPOSITORY = Symbol('ReceiptRepository');

// Register in module
@Module({
  providers: [
    { provide: RECEIPT_REPOSITORY, useClass: DrizzleReceiptRepository },
  ],
})

// Inject in service
@Injectable()
export class ReceiptService {
  constructor(
    @Inject(RECEIPT_REPOSITORY) private readonly repo: ReceiptRepository,
  ) {}
}

Prefer constructor injection

// ✅ CORRECT - Constructor injection
@Injectable()
export class ReceiptService {
  constructor(@Inject(RECEIPT_REPOSITORY) private readonly repo: ReceiptRepository) {}
}

// ❌ AVOID - Property injection
@Injectable()
export class ReceiptService {
  @Inject() repo: ReceiptRepository;
}

Quick Reference

Rule Convention
Module scope 1 module = 1 bounded context
Controllers Thin — delegate to services
Validation ZodValidationPipe in @Body()
Auth Guards at controller/route level
Error handling Global exception filters
DI for interfaces Symbol tokens + @Inject()
DI style Constructor injection only
File naming feature.type.ts pattern

04 同仓库更多 Skills

FabienSalles
FabienSalles/claude-marketplace

vitest-test-conventions

ACTIVATE when writing Vitest tests, creating test files, using vi.fn()/vi.mock()/vi.spyOn(), or test factories. ACTIVATE for 'Vitest', 'it.each', 'NestJS testing module', 'supertest', 'vi.fn', 'vi.mock', 'spyOn'. Provides Vitest/NestJS-specific testing patterns; cross-language testing principles (DAMP, AAA, spy over mock, what NOT to test) live in craft:testing-principles. DO NOT use for: node:test files (a file importing node:test) or a project whose tests run under node --test (see node-test:node-test-conventions), TDD workflow/iterations (see vitest:vitest-tdd-workflow), PHP/PHPUnit tests (see phpunit:php-test-conventions).

★ 9
FabienSalles
FabienSalles/claude-marketplace

vitest-tdd-workflow

ACTIVATE when building new features, endpoints, or user stories using TDD with Vitest in a TypeScript/NestJS context. ACTIVATE for '/feature-tdd-dev', 'TDD', 'red-green-refactor' in TS context. Provides Vitest/NestJS-specific TDD examples and commands; cross-language TDD workflow (cross-layer iterations, RED-GREEN-REFACTOR, working app, bug-fix-first-test, mocks-hiding-bugs) lives in craft:tdd-workflow-principles. DO NOT use for: node:test files (a file importing node:test) or a project whose tests run under node --test (see node-test:node-test-conventions), test writing conventions (see vitest:vitest-test-conventions), PHP TDD (see phpunit:php-tdd-workflow).

★ 9
FabienSalles
FabienSalles/claude-marketplace

ts-refactoring

ACTIVATE when refactoring TypeScript code. ACTIVATE for 'refactor', 'extract', 'redesign', 'simplify', or 'clean up' in a TypeScript / Node / NestJS context. This skill provides TS-specific examples for the cross-language refactoring rules defined in craft:refactoring-principles. DO NOT use for: writing new features from scratch, general OOP patterns (see ts-oop).

★ 9
FabienSalles
FabienSalles/claude-marketplace

ts-ports-adapters

ACTIVATE when a TypeScript codebase with no dependency-injection container has to declare a port and wire its adapter — a repository, a clock, an id generator, an event dispatcher the domain depends on. ACTIVATE for 'port', 'adapter', 'SPI', 'dependency inversion' or 'composition root' in a codebase that wires its dependencies by hand. Covers: the port as a type of functions in the domain layer, the adapter as an object literal annotated with it, the handler that takes its dependencies first and its data second, the composition root in the infrastructure layer, and the in-memory stub that substitutes for the adapter in a unit test. DO NOT use for: NestJS, or any container-based DI with decorators and tokens (see nest-ddd-conventions), aggregate operations and smart constructors (see ddd-ts-fp), the Result type itself (see ts-functional).

★ 9
FabienSalles
FabienSalles/claude-marketplace

ts-oop

ACTIVATE when designing TypeScript classes, and the value objects or collections modelled as classes, or when the user asks about object design, encapsulation, Tell Don't Ask, or Symbol.iterator. Provides TS-specific examples for the cross-language OOP rules defined in craft:oop-principles, plus TS-specific patterns (Symbol.iterator, branded types for primitive identifiers). DO NOT use for: a value object or an aggregate modelled as an immutable record rather than a class (see ddd-ts-fp), refactoring methodology (see ts-refactoring).

★ 9
FabienSalles
FabienSalles/claude-marketplace

ts-layer-boundaries

ACTIVATE when wiring a Worker entry point, a Router, a controller, or a domain event consumer in a TypeScript CQRS codebase, or when deciding where a port belongs. ACTIVATE for 'composition root', 'layer boundary', 'ESLint zones', 'domain must not import infrastructure'. Covers: the *Worker.ts composition root, the curried consumer, Router wiring of command endpoints, the five-gesture controller, the domain-to-infrastructure import boundary enforced by ESLint, infrastructure-only ports, in-memory doubles for every port, the read-can-reach-write asymmetry, and read endpoints going through a domain handler. DO NOT use for: the port's own shape and adapter binding (see ts-ports-adapters), the Result type (see ts-functional), domain event structure (see ts-ddd-events).

★ 9