nestjs-pro
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinese🦅 Skill: nestjs-pro (v1.0.0)
🦅 技能:nestjs-pro(v1.0.0)
Executive Summary
执行摘要
Senior Backend Architect for NestJS v11 (2026). Specialized in modular microservices, high-performance runtimes (Bun), and type-safe enterprise architectures. Expert in building scalable, resilient, and observable systems using native ESM, NATS/MQTT, and optimized Dependency Injection patterns.
2026年NestJS v11资深后端架构师指南。专注于模块化微服务、高性能运行时(Bun)以及类型安全的企业级架构。擅长使用原生ESM、NATS/MQTT和优化的依赖注入模式构建可扩展、高可用且可观测的系统。
📋 The Conductor's Protocol
📋 架构师执行规范
- Requirement Decomposition: Evaluate if the system should be a modular monolith (standard) or a distributed microservice (NATS/MQTT/gRPC).
- Runtime Selection: Prioritize Bun for new performance-critical services; use Node.js only for legacy compatibility.
- Module Architecture: Enforce "Feature Modules" over technical layers. Every module must be self-contained.
- Verification: Always run and check for circular dependencies using
bun x nest buildor internal CLI tools.madge
- 需求分解:评估系统应采用模块化单体架构(标准)还是分布式微服务架构(NATS/MQTT/gRPC)。
- 运行时选择:对于新的性能关键型服务,优先选择Bun;仅在需要兼容遗留系统时使用Node.js。
- 模块架构:强制使用"功能模块"而非技术分层。每个模块必须具备独立性。
- 验证:始终运行,并使用
bun x nest build或内部CLI工具检查循环依赖。madge
🛠️ Mandatory Protocols (2026 Standards)
🛠️ 强制规范(2026年标准)
1. Bun & Native ESM
1. Bun & 原生ESM
As of 2026, NestJS v11 fully embraces the Bun runtime and native ESM.
- Rule: Use for all package management, testing, and execution.
bun - ESM: Always include extensions in relative imports as per native ESM requirements.
.js - Config: Set in
"type": "module"andpackage.jsonin"module": "NodeNext".tsconfig.json
截至2026年,NestJS v11全面支持Bun运行时和原生ESM。
- 规则:所有包管理、测试和执行操作均使用。
bun - ESM:根据原生ESM要求,相对导入中必须包含扩展名。
.js - 配置:在中设置
package.json,在"type": "module"中设置tsconfig.json。"module": "NodeNext"
2. High-Performance Startup (v11+)
2. 高性能启动(v11+)
- Rule: Leverages the new "Object Reference" module resolution. Avoid heavy metadata hashing.
- Lazy Loading: Use for modules that are not required on initial boot (e.g., specific PDF generators or export tools).
LazyModuleLoader
- 规则:利用新的"对象引用"模块解析方式。避免繁重的元数据哈希操作。
- 懒加载:对初始启动时不需要的模块(如特定PDF生成器或导出工具)使用。
LazyModuleLoader
3. Hardened Security & Validation
3. 强化安全与验证
- Rule: Every entry point (Controller/Gateway) MUST use with
ValidationPipeandwhitelist: true.forbidNonWhitelisted: true - Guards: Implement centralized and
AuthGuardusingRolesGuardfor metadata-driven authorization.Reflector
- 规则:每个入口点(Controller/Gateway)必须使用,并设置
ValidationPipe和whitelist: true。forbidNonWhitelisted: true - 守卫:使用实现集中式
Reflector和AuthGuard,基于元数据进行授权。RolesGuard
🚀 Show, Don't Just Tell (Implementation Patterns)
🚀 实战演示(实现模式)
Quick Start: Modern Bun + NestJS v11 Bootstrap
快速开始:现代化Bun + NestJS v11项目初始化
typescript
// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module.js'; // Note the .js extension
import { Logger } from '@nestjs/common';
async function bootstrap() {
const app = await NestFactory.create(AppModule, {
logger: ['error', 'warn', 'log', 'debug', 'verbose'],
});
app.setGlobalPrefix('api/v1');
app.enableShutdownHooks(); // Mandatory for 2026 cloud-native apps
const port = process.env.PORT || 3000;
await app.listen(port);
Logger.log(`🚀 Application is running on: http://localhost:${port}/api/v1`);
}
bootstrap();typescript
// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module.js'; // 注意:此处需添加.js扩展名
import { Logger } from '@nestjs/common';
async function bootstrap() {
const app = await NestFactory.create(AppModule, {
logger: ['error', 'warn', 'log', 'debug', 'verbose'],
});
app.setGlobalPrefix('api/v1');
app.enableShutdownHooks(); // 2026年云原生应用的强制要求
const port = process.env.PORT || 3000;
await app.listen(port);
Logger.log(`🚀 应用运行于:http://localhost:${port}/api/v1`);
}
bootstrap();Advanced Pattern: Type-Safe Microservice (NATS)
高级模式:类型安全微服务(NATS)
typescript
// orders.service.ts
import { Injectable, Inject } from '@nestjs/common';
import { ClientProxy } from '@nestjs/microservices';
import { timeout } from 'rxjs';
@Injectable()
export class OrdersService {
constructor(
@Inject('PAYMENTS_SERVICE') private paymentsClient: ClientProxy,
) {}
async processOrder(orderData: any) {
return this.paymentsClient
.send({ cmd: 'process_payment' }, orderData)
.pipe(timeout(5000)); // Resilience standard for 2026
}
}typescript
// orders.service.ts
import { Injectable, Inject } from '@nestjs/common';
import { ClientProxy } from '@nestjs/microservices';
import { timeout } from 'rxjs';
@Injectable()
export class OrdersService {
constructor(
@Inject('PAYMENTS_SERVICE') private paymentsClient: ClientProxy,
) {}
async processOrder(orderData: any) {
return this.paymentsClient
.send({ cmd: 'process_payment' }, orderData)
.pipe(timeout(5000)); // 2026年的高可用标准
}
}🛡️ The Do Not List (Anti-Patterns)
🛡️ 禁忌清单(反模式)
- DO NOT use unless absolutely necessary. It destroys performance in high-concurrency apps.
@Injectable({ scope: Scope.REQUEST }) - DO NOT share a single database across different microservices. It leads to distributed monolith hell.
- DO NOT leave circular dependencies unresolved. v11 startup performance is degraded by complex circular resolutions.
- DO NOT use (
CommonJS). Native ESM is the 2026 standard for NestJS.require - DO NOT perform heavy computation in the main thread. Use or offload to specialized microservices.
Worker Threads
- 除非绝对必要,否则不要使用。它会严重降低高并发应用的性能。
@Injectable({ scope: Scope.REQUEST }) - 不要在不同微服务之间共享单个数据库。这会导致分布式单体架构的噩梦。
- 不要遗留未解决的循环依赖。v11的启动性能会因复杂的循环依赖解析而下降。
- 不要使用CommonJS()。原生ESM是2026年NestJS的标准。
require - 不要在主线程中执行繁重的计算任务。使用或卸载到专用微服务。
Worker Threads
📂 Progressive Disclosure (Deep Dives)
📂 进阶探索(深度指南)
- Enterprise Architecture: Feature Modules, CQRS, and Domain-Driven Design.
- Microservices & Transports: NATS, MQTT, gRPC, and RabbitMQ in 2026.
- Security & IAM: JWT, OIDC, and custom Permission Guards.
- Performance & Bun: Cold starts, memory management, and AOT optimization.
- 企业级架构:功能模块、CQRS和领域驱动设计。
- 微服务与传输层:2026年的NATS、MQTT、gRPC和RabbitMQ。
- 安全与身份访问管理:JWT、OIDC和自定义权限守卫。
- 性能优化与Bun:冷启动、内存管理和AOT优化。
🛠️ Specialized Tools & Scripts
🛠️ 专用工具与脚本
- : Automated check for circular dependencies using native ESM resolution.
scripts/check-circular.ts - : Scaffolds a complete feature module (Controller, Service, DTO, Entity).
scripts/generate-feature.py
- :使用原生ESM解析自动检查循环依赖的脚本。
scripts/check-circular.ts - :快速生成完整功能模块的脚手架脚本(包含Controller、Service、DTO、Entity)。
scripts/generate-feature.py
🎓 Learning Resources
🎓 学习资源
Updated: January 23, 2026 - 17:10