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

📋 架构师执行规范

  1. Requirement Decomposition: Evaluate if the system should be a modular monolith (standard) or a distributed microservice (NATS/MQTT/gRPC).
  2. Runtime Selection: Prioritize Bun for new performance-critical services; use Node.js only for legacy compatibility.
  3. Module Architecture: Enforce "Feature Modules" over technical layers. Every module must be self-contained.
  4. Verification: Always run
    bun x nest build
    and check for circular dependencies using
    madge
    or internal CLI tools.

  1. 需求分解:评估系统应采用模块化单体架构(标准)还是分布式微服务架构(NATS/MQTT/gRPC)。
  2. 运行时选择:对于新的性能关键型服务,优先选择Bun;仅在需要兼容遗留系统时使用Node.js。
  3. 模块架构:强制使用"功能模块"而非技术分层。每个模块必须具备独立性。
  4. 验证:始终运行
    bun x nest build
    ,并使用
    madge
    或内部CLI工具检查循环依赖。

🛠️ 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
    bun
    for all package management, testing, and execution.
  • ESM: Always include
    .js
    extensions in relative imports as per native ESM requirements.
  • Config: Set
    "type": "module"
    in
    package.json
    and
    "module": "NodeNext"
    in
    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
    LazyModuleLoader
    for modules that are not required on initial boot (e.g., specific PDF generators or export tools).
  • 规则:利用新的"对象引用"模块解析方式。避免繁重的元数据哈希操作。
  • 懒加载:对初始启动时不需要的模块(如特定PDF生成器或导出工具)使用
    LazyModuleLoader

3. Hardened Security & Validation

3. 强化安全与验证

  • Rule: Every entry point (Controller/Gateway) MUST use
    ValidationPipe
    with
    whitelist: true
    and
    forbidNonWhitelisted: true
    .
  • Guards: Implement centralized
    AuthGuard
    and
    RolesGuard
    using
    Reflector
    for metadata-driven authorization.

  • 规则:每个入口点(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)

🛡️ 禁忌清单(反模式)

  1. DO NOT use
    @Injectable({ scope: Scope.REQUEST })
    unless absolutely necessary. It destroys performance in high-concurrency apps.
  2. DO NOT share a single database across different microservices. It leads to distributed monolith hell.
  3. DO NOT leave circular dependencies unresolved. v11 startup performance is degraded by complex circular resolutions.
  4. DO NOT use
    CommonJS
    (
    require
    ). Native ESM is the 2026 standard for NestJS.
  5. DO NOT perform heavy computation in the main thread. Use
    Worker Threads
    or offload to specialized microservices.

  1. 除非绝对必要,否则不要使用
    @Injectable({ scope: Scope.REQUEST })
    。它会严重降低高并发应用的性能。
  2. 不要在不同微服务之间共享单个数据库。这会导致分布式单体架构的噩梦。
  3. 不要遗留未解决的循环依赖。v11的启动性能会因复杂的循环依赖解析而下降。
  4. 不要使用CommonJS(
    require
    )。原生ESM是2026年NestJS的标准。
  5. 不要在主线程中执行繁重的计算任务。使用
    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

🛠️ 专用工具与脚本

  • scripts/check-circular.ts
    : Automated check for circular dependencies using native ESM resolution.
  • scripts/generate-feature.py
    : Scaffolds a complete feature module (Controller, Service, DTO, Entity).

  • scripts/check-circular.ts
    :使用原生ESM解析自动检查循环依赖的脚本。
  • scripts/generate-feature.py
    :快速生成完整功能模块的脚手架脚本(包含Controller、Service、DTO、Entity)。

🎓 Learning Resources

🎓 学习资源