nestjs-best-practices by giuseppe-trisciuoglio/developer-kit
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill nestjs-best-practices此技能提供了一套精心策划的最佳实践,用于构建生产级的 NestJS 应用程序。所有指南均基于 官方 NestJS 文档,并强制执行一致、可维护和可扩展的模式。
class-validator 和 ValidationPipe 验证 DTO 时遵循严格的模块封装。每个领域功能都应该是其独立的 @Module():
forwardRef() 处理循环依赖;优先考虑重构SharedModule 处理横切关注点(日志记录、配置、缓存)广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
查看 references/arch-module-boundaries.md 获取强制执行规则。
根据用例选择正确的提供者作用域:
| 作用域 | 生命周期 | 用例 |
|---|---|---|
DEFAULT | 单例(共享) | 无状态服务、仓库 |
REQUEST | 每个请求实例 | 请求作用域的数据(租户、用户上下文) |
TRANSIENT | 每次注入新实例 | 有状态的工具、每个消费者的缓存 |
DEFAULT 作用域 —— 仅在理由充分时使用 REQUEST 或 TRANSIENTuseClass、useValue、useFactory 或 useExisting 注册自定义提供者查看 references/di-provider-scoping.md 获取强制执行规则。
理解并遵循 NestJS 请求处理管道:
Middleware → Guards → Interceptors (before) → Pipes → Route Handler → Interceptors (after) → Exception Filters
true/false)在整个应用程序中标准化错误响应:
HttpException 用于 HTTP 特定错误OrderNotFoundException)ExceptionFilter 以保持错误格式一致查看 references/error-exception-filters.md 获取强制执行规则。
在 API 边界强制执行输入验证:
ValidationPipe,设置 transform: true 和 whitelist: trueclass-validator 装饰器装饰所有 DTO 属性class-transformer 进行类型转换(@Type()、@Transform())查看 references/api-validation-dto.md 获取强制执行规则。
遵循 NestJS 提供者约定集成 Drizzle ORM:
查看 references/db-drizzle-patterns.md 获取强制执行规则。
| 领域 | 应该做 | 不应该做 |
|---|---|---|
| 模块 | 每个领域功能一个模块 | 将所有内容都堆在 AppModule 中 |
| 依赖注入作用域 | 默认使用单例作用域 | 没有正当理由就使用 REQUEST 作用域 |
| 错误处理 | 自定义异常过滤器 + 领域错误 | 在控制器中使用裸 try/catch 和 console.log |
| 验证 | 全局 ValidationPipe + DTO 装饰器 | 在控制器中进行手动 if 检查 |
| 数据库 | 使用注入客户端的仓库模式 | 在控制器中直接进行数据库查询 |
| 测试 | 单元测试服务,端到端测试控制器 | 跳过测试或测试实现细节 |
| 配置 | 使用带类型化模式的 @nestjs/config | 硬编码值或直接使用 process.env |
构建新的“产品”功能时:
// product/product.module.ts
@Module({
imports: [DatabaseModule],
controllers: [ProductController],
providers: [ProductService, ProductRepository],
exports: [ProductService],
})
export class ProductModule {}
// product/dto/create-product.dto.ts
import { IsString, IsNumber, IsPositive, MaxLength } from 'class-validator';
export class CreateProductDto {
@IsString()
@MaxLength(255)
readonly name: string;
@IsNumber()
@IsPositive()
readonly price: number;
}
@Injectable()
export class ProductService {
constructor(private readonly productRepository: ProductRepository) {}
async findById(id: string): Promise<Product> {
const product = await this.productRepository.findById(id);
if (product === null) {
throw new ProductNotFoundException(id);
}
return product;
}
}
REQUEST 作用域的提供者会级联到所有依赖项forwardRef() —— 重构模块以消除循环依赖ValidationPipe —— 始终在 API 边界使用 DTO 进行验证@nestjs/configreferences/architecture.md —— NestJS 架构模式深度解析references/ —— 包含正确/错误示例的单个强制执行规则assets/templates/ —— 常见 NestJS 组件的入门模板每周安装量
127
代码仓库
GitHub 星标数
173
首次出现
2026年2月28日
安全审计
安装于
gemini-cli113
codex112
github-copilot109
kimi-cli107
amp107
cline107
This skill provides a curated set of best practices for building production-grade NestJS applications. All guidelines are grounded in the Official NestJS Documentation and enforce consistent, maintainable, and scalable patterns.
class-validator and ValidationPipeFollow strict module encapsulation. Each domain feature should be its own @Module():
forwardRef() only as a last resort for circular dependencies; prefer restructuringSharedModule for cross-cutting concerns (logging, configuration, caching)See references/arch-module-boundaries.md for enforcement rules.
Choose the correct provider scope based on use case:
| Scope | Lifecycle | Use Case |
|---|---|---|
DEFAULT | Singleton (shared) | Stateless services, repositories |
REQUEST | Per-request instance | Request-scoped data (tenant, user context) |
TRANSIENT | New instance per injection | Stateful utilities, per-consumer caches |
DEFAULT scope — only use REQUEST or TRANSIENT when justifieduseClass, useValue, useFactory, or useExistingSee references/di-provider-scoping.md for enforcement rules.
Understand and respect the NestJS request processing pipeline:
Middleware → Guards → Interceptors (before) → Pipes → Route Handler → Interceptors (after) → Exception Filters
true/false)Standardize error responses across the application:
HttpException for HTTP-specific errorsOrderNotFoundException)ExceptionFilter for consistent error formattingSee references/error-exception-filters.md for enforcement rules.
Enforce input validation at the API boundary:
ValidationPipe globally with transform: true and whitelist: trueclass-validator decoratorsclass-transformer for type coercion (@Type(), @Transform())See references/api-validation-dto.md for enforcement rules.
Integrate Drizzle ORM following NestJS provider conventions:
See references/db-drizzle-patterns.md for enforcement rules.
| Area | Do | Don't |
|---|---|---|
| Modules | One module per domain feature | Dump everything in AppModule |
| DI Scoping | Default to singleton scope | Use REQUEST scope without justification |
| Error Handling | Custom exception filters + domain errors | Bare try/catch with console.log |
| Validation | Global ValidationPipe + DTO decorators | Manual if checks in controllers |
When building a new "Product" feature:
// product/product.module.ts
@Module({
imports: [DatabaseModule],
controllers: [ProductController],
providers: [ProductService, ProductRepository],
exports: [ProductService],
})
export class ProductModule {}
// product/dto/create-product.dto.ts
import { IsString, IsNumber, IsPositive, MaxLength } from 'class-validator';
export class CreateProductDto {
@IsString()
@MaxLength(255)
readonly name: string;
@IsNumber()
@IsPositive()
readonly price: number;
}
@Injectable()
export class ProductService {
constructor(private readonly productRepository: ProductRepository) {}
async findById(id: string): Promise<Product> {
const product = await this.productRepository.findById(id);
if (product === null) {
throw new ProductNotFoundException(id);
}
return product;
}
}
REQUEST-scoped providers cascade to all dependentsforwardRef() — restructure modules to eliminate circular dependenciesValidationPipe — always validate at the API boundary with DTOs@nestjs/config with environment variablesreferences/architecture.md — Deep-dive into NestJS architectural patternsreferences/ — Individual enforcement rules with correct/incorrect examplesassets/templates/ — Starter templates for common NestJS componentsWeekly Installs
127
Repository
GitHub Stars
173
First Seen
Feb 28, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
gemini-cli113
codex112
github-copilot109
kimi-cli107
amp107
cline107
代码安全审查清单:最佳实践与漏洞防范指南(含密钥管理、SQL注入防护)
1,700 周安装
| Database | Repository pattern with injected client | Direct DB queries in controllers |
| Testing | Unit test services, e2e test controllers | Skip tests or test implementation details |
| Configuration | @nestjs/config with typed schemas | Hardcode values or use process.env |