界面已本地化;技能介绍与说明文档按所选语言由 AI 自动翻译,代码、命令、路径和专业术语保留原文,以原作者文档为准。
探索技能
开发与工程 · SKILL.md

nestjs-api

nestjs-api

【开发与工程】This skill provides patterns and templates for NestJS 11.x with Fastify, Prisma ORM, and TypeScript 5.x development. It should be activated when creating NestJS modules, controllers, services, DTOs, guards, interceptors, or tests.

独立 GitHub 快照 · 自动分类 · 以原作者文档为准

技能说明

GitHub

name: nestjs-api description: This skill provides patterns and templates for NestJS 11.x with Fastify, Prisma ORM, and TypeScript 5.x development. It should be activated when creating NestJS modules, controllers, services, DTOs, guards, interceptors, or tests. allowed-tools: Bash, Read, Write, Edit metadata: triggers: NestJS, Nest, TypeScript backend, NestJS module, NestJS controller, NestJS service, Fastify, Prisma, NestJS guard related-skills: nestjs-coding-standard, openapi-spec-generation, database-schema-designer domain: backend role: specialist scope: implementation output-format: code last-reviewed: "2026-03-14"

Iron Law

NO NESTJS MODULE WITHOUT READING reference/nestjs-conventions.md FIRST — Fastify adapter quirks, Prisma 7.x patterns, and DTO validation rules are defined there

NestJS 11.x + Fastify + Prisma REST API Skill

Conventions & Rules

For code conventions, package layout, NestJS rules, Prisma 7.x rules, and environment file rules, read reference/nestjs-conventions.md

Quick Scaffold — New NestJS Project

# Using NestJS CLI
npx @nestjs/cli new my-service --package-manager npm --strict

Process

  1. Scaffold using NestJS CLI or the command above
  2. Configure package.json and tsconfig — read reference/nestjs-config-basics.md, reference/nestjs-config-npm-ts.md, and reference/nestjs-config-prisma7.md
  3. Create files using templates — read reference/nestjs-templates-core.md for main.ts, AppModule, CoreModule; read reference/nestjs-templates-features.md for feature modules, controllers, services, DTOs
  4. Follow conventions below for package layout and NestJS rules
  5. Write tests with Vitest + supertest or NestJS Testing utilities
  6. Format and check: npm run lint && npm run typecheck

Key Patterns

PatternImplementation
Modules@Module() with imports/providers/exports, aggregation pattern
Controllers@Controller('api/v1/...') with route decorators
Services@Injectable() with constructor injection
DTOsClasses with class-validator decorators (@IsString(), @IsNotEmpty())
RepositoriesPrisma Client via DatabaseService wrapper
Error handling@Catch() exception filter returning ProblemDetail (RFC 9457)
ConfigFail-fast registerAs() with static config reader
MigrationsPrisma Migrate in prisma/migrations/
Guards@UseGuards() for auth (JwtAuthGuard, RolesGuard)
InterceptorsLoggingInterceptor, TransformInterceptor (global)
PipesGlobal ValidationPipe with whitelist and transform

Reference Files

FileContentLoad When
reference/nestjs-config-basics.mdStatic config reader, config module aggregation, fail-fast validationProject setup, initial configuration
reference/nestjs-config-npm-ts.mdpackage.json with dependencies, tsconfig.jsonProject setup, configuring dependencies
reference/nestjs-config-prisma7.mdPrisma 7.x schema, prisma.config.ts, PrismaService, .env templateSetting up database, writing Prisma queries
reference/nestjs-templates-core.mdmain.ts, app.module, core.module templatesBootstrapping app, creating core module
reference/nestjs-templates-features.mdFeature module, controller, service, DTO templatesCreating modules, controllers, services
reference/nestjs-templates-infrastructure.mdDockerfile, docker-compose, Vitest configContainerizing app, configuring test runner
reference/nestjs-enterprise-patterns.mdException hierarchy, validation pipe, API versioningImplementing error handling, input validation, API versioning
reference/nestjs-enterprise-infrastructure.mdSecurity middleware (Helmet), rate limiting, Swagger, health checksAdding security headers, rate limiting, API documentation
reference/nestjs-resilience-circuit-breaker.mdCircuit breaker, retry, timeout, database fallbackAdding resilience patterns, handling service failures
reference/nestjs-resilience-context.mdRequest context with AsyncLocalStorage, correlation IDsAdding request tracing, correlation IDs
reference/nestjs-feature-flags.mdFeature flags service, Redis fallback, gradual rolloutImplementing feature flags, gradual rollout
reference/nestjs-observability.mdOpenTelemetry tracing/metrics, structured logging, cloud loggingAdding observability, structured logging, tracing
reference/nestjs-messaging-basics.mdBullMQ queues, background job processingAdding background jobs, queue processing
reference/nestjs-messaging-queues.mdRabbitMQ reliable messaging, dead letter queuesImplementing RabbitMQ messaging, dead letter queues
reference/nestjs-messaging-streaming.mdKafka event streaming, high-throughput patternsImplementing Kafka streaming, high-throughput events
reference/nestjs-testing-unit-basics.mdUnit testing with Vitest, service test patternsWriting unit tests for services
reference/nestjs-testing-unit-controllers.mdController unit tests, test data factoriesWriting unit tests for controllers
reference/nestjs-testing-unit-mocks.mdPrisma/Redis/HTTP mocking, ConfigService mockingMocking dependencies in unit tests
reference/nestjs-testing-integration-setup.mdE2E testing setup, Testcontainers, supertestWriting integration tests, E2E tests
reference/nestjs-testing-integration-patterns.mdAuth testing, validation, pagination patternsTesting auth flows, pagination, validation
reference/nestjs-testing-patterns.mdCircuit breaker testing, AsyncLocalStorage testingTesting resilience patterns, context propagation
reference/nestjs-testing-ci-troubleshooting.mdCoverage standards, CI/CD, troubleshootingConfiguring CI pipelines, coverage thresholds
reference/nestjs-rest-workflow.mdREST workflow, OpenAPI/Swagger controller setupDesigning REST endpoints, setting up Swagger
reference/nestjs-rest-dto-pagination.mdDTO mapping, pagination, filter patternsCreating DTOs, implementing pagination
reference/nestjs-rest-upload-errors.mdFile uploads, API versioning, ProblemDetail errorsImplementing file uploads, error responses
reference/nestjs-rest-services.mdService patterns, external API clients, bulk operations, soft deleteWriting service logic, calling external APIs
reference/nestjs-security-auth.mdJWT authentication (RS256), password hashing, token managementImplementing JWT auth, implementing guards
reference/nestjs-security-scanning.mdOWASP scanning, security headers, static analysisSecurity auditing, dependency scanning
reference/nestjs-security-validation-logging.mdInput validation, PII masking, Prisma securitySecuring input handling, masking sensitive data
reference/nestjs-debugging-logging.mdDebug mode, Prisma query logging, Fastify lifecycleDebugging requests, tracing Prisma queries
reference/nestjs-debugging-context-di.mdAsyncLocalStorage context, DI debugging, configDebugging DI issues, context propagation
reference/nestjs-debugging-performance.mdMemory leaks, performance profilingDiagnosing memory leaks, profiling performance
reference/nestjs-debugging-production.mdProduction debugging, structured logging, tracingDebugging production issues, structured logging
reference/nestjs-review-checklist.mdNestJS review checklist (used by nestjs-reviewer agent)Code review, pre-PR checklist
reference/nestjs-real-world-issues.md9 framework-level issues from GitHub/SO with frequency ratings and Vitest-adapted solutionsDebugging DI errors, circular deps, JWT config, memory leaks
reference/nestjs-decision-trees.mdDecision trees for module organization, auth method, testing strategy, caching, error responsesArchitecture decisions before implementation

Common Commands

npm run start:dev                           # Run in dev mode (watch)
npm test                                    # Run unit tests (Vitest)
npm run test:e2e                            # Run integration/E2E tests
npm run test:cov                            # Run tests with coverage report
npm run lint                                # ESLint check
npm run typecheck                           # TypeScript type-check only
npm run build                               # Compile TypeScript
npx prisma migrate dev --name <migration>   # Create and run migration
npx prisma generate                         # Regenerate Prisma client after schema change
npx prisma studio                           # Open Prisma Studio GUI

Documentation Sources

Before generating code, consult these sources for current syntax and APIs:

SourceURL / ToolPurpose
Prisma ORMhttps://www.prisma.io/docs/llms.txtPrisma schema, migrations, client API
NestJS / TypeScriptContext7 MCPLatest NestJS decorators, modules, patterns

Error Handling

Validation errors: Use class-validator decorators on DTO classes. Global ValidationPipe auto-returns 422 with details.

Not-found errors: Throw NotFoundException from services. Global exception filter returns structured 404.

Duplicate errors: Catch Prisma P2002 unique constraint violation and convert to 409 Conflict.

Hard Prohibitions

  • No raw any request bodies — all endpoints must use DTOs with class-validator decorators
  • No raw SQL unless performance-critical (document why in a comment)
  • No jest in new code — use Vitest exclusively
  • @UseGuards(JwtAuthGuard) on every non-public route — no exceptions
  • No arbitrary Tailwind values (p-[13px]) — use the scale (p-4, gap-6)
  • Angular: no *ngIf/*ngFor — use @if/@for/@switch; typed reactive forms FormGroup<T> only

Post-Code Review

After writing TypeScript code, dispatch these reviewer agents:

  • nestjs-reviewer — module correctness, Prisma usage, resilience patterns
  • code-reviewer — general quality, DRY, error handling
  • security-reviewer — auth, input validation, OWASP Top 10
我的收藏