Communitygithub.com

NestJS-Entwicklungsmuster

NestJS-Architekturmuster für Module, Controller, Provider, DTO-Validierung, Guards, Interceptors, Konfiguration und produktionsreife TypeScript-Backends. Verwenden Sie dies beim Entwickeln oder Überprüfen eines NestJS-Backends.

Was ist NestJS-Entwicklungsmuster?

Diese Skill-Definition beschreibt eine umfassende Sammlung von NestJS-Entwicklungsmustern für modulare, produktionsreife TypeScript-Backends. Sie deckt die gesamte Architektur ab: von der Projektstruktur mit domänenzentrierten Feature-Modulen und einem gemeinsamen `common/`-Ordner für querschnittliche Belange, über bewährte Methoden zum Bootstrapping mit globaler Validierung, bis hin zu DTOs, Guards, Exception-Filtern und Konfiguration. Die Skill-Anleitung betont schlanke Controller, injizierbare Services für Geschäftslogik, konsistente Fehlerstrukturen und umgebungsbewusste Konfiguration. Sie wird auf Plattformen wie Claude Code, Cursor oder Codex aktiviert, wenn ein Nutzer ein NestJS-API oder -Service erstellt oder überprüft. Die Anleitung enthält konkrete Codebeispiele für Module, Controller, Services, DTOs mit `class-validator`, Authentifizierungs-Guards, Exception-Filter und Tests, und stellt sicher, dass alle Best Practices wie Whitelist-Validierung, Typisierung und asynchrone Initialisierung befolgt werden.

Funktioniert mit~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/nestjs-patterns

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Dokumentation

Was macht NestJS-Entwicklungsmuster?

Produktionsreife NestJS-Muster für modulare TypeScript-Backends.

Wann aktivieren

  • Erstellen von NestJS-APIs oder -Services
  • Strukturieren von Modulen, Controllern und Providern
  • Hinzufügen von DTO-Validierung, Guards, Interceptors oder Exception-Filtern
  • Konfigurieren umgebungsabhängiger Einstellungen und Datenbankintegrationen
  • Testen von NestJS-Einheiten oder HTTP-Endpunkten

Projektstruktur

src/
├── app.module.ts
├── main.ts
├── common/
│   ├── filters/
│   ├── guards/
│   ├── interceptors/
│   └── pipes/
├── config/
│   ├── configuration.ts
│   └── validation.ts
├── modules/
│   ├── auth/
│   │   ├── auth.controller.ts
│   │   ├── auth.module.ts
│   │   ├── auth.service.ts
│   │   ├── dto/
│   │   ├── guards/
│   │   └── strategies/
│   └── users/
│       ├── dto/
│       ├── entities/
│       ├── users.controller.ts
│       ├── users.module.ts
│       └── users.service.ts
└── prisma/ oder database/
  • Halten Sie den Domain-Code innerhalb der Feature-Module.
  • Platzieren Sie querschnittliche Filter, Dekorateure, Guards und Interceptors in common/.
  • Behalten Sie DTOs in der Nähe des Moduls, dem sie gehören.

Bootstrap und globale Validierung

async function bootstrap() {
  const app = await NestFactory.create(AppModule, { bufferLogs: true });

  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      forbidNonWhitelisted: true,
      transform: true,
      transformOptions: { enableImplicitConversion: true },
    }),
  );

  app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)));
  app.useGlobalFilters(new HttpExceptionFilter());

  await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
  • Aktivieren Sie immer whitelist und forbidNonWhitelisted für öffentliche APIs.
  • Bevorzugen Sie eine globale Validierungspipe anstelle wiederholter Validierungskonfiguration pro Route.

Module, Controller und Provider

@Module({
  controllers: [UsersController],
  providers: [UsersService],
  exports: [UsersService],
})
export class UsersModule {}

@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Get(':id')
  getById(@Param('id', ParseUUIDPipe) id: string) {
    return this.usersService.getById(id);
  }

  @Post()
  create(@Body() dto: CreateUserDto) {
    return this.usersService.create(dto);
  }
}

@Injectable()
export class UsersService {
  constructor(private readonly usersRepo: UsersRepository) {}

  async create(dto: CreateUserDto) {
    return this.usersRepo.create(dto);
  }
}
  • Controller sollten schlank bleiben: HTTP-Eingaben parsen, einen Provider aufrufen und Antwort-DTOs zurückgeben.
  • Platzieren Sie Geschäftslogik in injizierbaren Services, nicht in Controllern.
  • Exportieren Sie nur die Provider, die andere Module tatsächlich benötigen.

DTOs und Validierung

export class CreateUserDto {
  @IsEmail()
  email!: string;

  @IsString()
  @Length(2, 80)
  name!: string;

  @IsOptional()
  @IsEnum(UserRole)
  role?: UserRole;
}
  • Validieren Sie jedes Request-DTO mit class-validator.
  • Verwenden Sie dedizierte Antwort-DTOs oder Serializer, anstatt ORM-Entitäten direkt zurückzugeben.
  • Vermeiden Sie das Durchsickern interner Felder wie Passwort-Hashes, Tokens oder Audit-Spalten.

Authentifizierung, Guards und Request-Kontext

@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('admin')
@Get('admin/report')
getAdminReport(@Req() req: AuthenticatedRequest) {
  return this.reportService.getForUser(req.user.id);
}
  • Halten Sie Auth-Strategien und Guards modullokal, es sei denn, sie sind wirklich gemeinsam genutzt.
  • Kodieren Sie grobe Zugriffsregeln in Guards und führen Sie ressourcenspezifische Autorisierung in Services durch.
  • Bevorzugen Sie explizite Request-Typen für authentifizierte Request-Objekte.

Exception-Filter und Fehlerstruktur

@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const response = host.switchToHttp().getResponse<Response>();
    const request = host.switchToHttp().getRequest<Request>();

    if (exception instanceof HttpException) {
      return response.status(exception.getStatus()).json({
        path: request.url,
        error: exception.getResponse(),
      });
    }

    return response.status(500).json({
      path: request.url,
      error: 'Interner Serverfehler',
    });
  }
}
  • Verwenden Sie eine einheitliche Fehlerhülle über die gesamte API hinweg.
  • Werfen Sie Framework-Ausnahmen für erwartete Client-Fehler; protokollieren und umschließen Sie unerwartete Fehler zentral.

Konfiguration und Umgebungsvalidierung

ConfigModule.forRoot({
  isGlobal: true,
  load: [configuration],
  validate: validateEnv,
});
  • Validieren Sie Umgebungsvariablen beim Start, nicht erst bei der ersten Anfrage.
  • Greifen Sie auf die Konfiguration nur über typisierte Hilfsfunktionen oder Konfigurationsservices zu.
  • Trennen Sie Entwicklungs-/Staging-/Produktions-Aspekte in Konfigurationsfabriken, anstatt sie im Feature-Code zu verzweigen.

Persistenz und Transaktionen

  • Halten Sie Repository-/ORM-Code hinter Providern, die die Domänensprache sprechen.
  • Isolieren Sie bei Prisma oder TypeORM transaktionale Arbeitsabläufe in Services, die die Arbeitseinheit besitzen.
  • Lassen Sie Controller keine mehrschrittigen Schreibvorgänge direkt koordinieren.

Testen

describe('UsersController', () => {
  let app: INestApplication;

  beforeAll(async () => {
    const moduleRef = await Test.createTestingModule({
      imports: [UsersModule],
    }).compile();

    app = moduleRef.createNestApplication();
    app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));
    await app.init();
  });
});
  • Testen Sie Provider isoliert mit gemockten Abhängigkeiten.
  • Fügen Sie Request-Level-Tests für Guards, Validierungspipes und Exception-Filter hinzu.
  • Verwenden Sie in Tests dieselben globalen Pipes/Filter wie in der Produktion.

Produktionsstandards

  • Aktivieren Sie strukturierte Protokollierung und Request-Korrelations-IDs.
  • Beenden Sie den Prozess bei ungültiger Umgebung/Konfiguration, anstatt nur teilweise zu starten.
  • Bevorzugen Sie asynchrone Provider-Initialisierung für DB/Cache-Clients mit expliziten Health-Checks.
  • Halten Sie Hintergrundjobs und Event-Consumer in eigenen Modulen, nicht innerhalb von HTTP-Controllern.
  • Machen Sie Ratenbegrenzung, Authentifizierung und Audit-Protokollierung für öffentliche Endpunkte explizit.

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

Verwandte Skills