affaan-m/ECC

nestjs-patterns

NestJS 架构模式,涵盖模块、控制器、提供者、DTO 验证、守卫、拦截器、配置以及生产级 TypeScript 后端。

66CollectingNetwork access
See how to use itView GitHub source
npx skills add https://github.com/affaan-m/ECC --skill "docs/zh-CN/skills/nestjs-patterns"
Automated source guide

Source checked Jul 28, 2026·Refresh due Oct 26, 2026

Reorganized from the pinned upstream SKILL.md

Turn nestjs-patterns's source instructions into a guide you can follow

According to the pinned SKILL.md from affaan-m/ECC: 适用于模块化 TypeScript 后端的生产级 NestJS 模式。

npx skills add https://github.com/affaan-m/ECC --skill "docs/zh-CN/skills/nestjs-patterns"
Check the pinned source

Best fit

  • NestJS 架构模式,涵盖模块、控制器、提供者、DTO 验证、守卫、拦截器、配置以及生产级 TypeScript 后端。

Bring this context

  • A concrete task that matches the documented purpose of nestjs-patterns.
  • The files, examples, or context the task depends on.
  • Your constraints, target environment, and definition of done.

Expected outputs

  • A result that follows the pinned nestjs-patterns instructions.
  • A concise record of assumptions, inputs used, and unresolved questions.
  • A final check against the source workflow and relevant permission signals.

Key source sections

Read nestjs-patterns through these 5 source sections

Sections are extracted automatically from the pinned SKILL.md and link back to the source.

01

何时启用

构建 NestJS API 或服务时 组织模块、控制器和提供者时 添加 DTO 验证、守卫、拦截器或异常过滤器时 配置环境感知设置和数据库集成时 测试 NestJS 单元或 HTTP 端点时

SKILL.md · 何时启用
构建 NestJS API 或服务时组织模块、控制器和提供者时添加 DTO 验证、守卫、拦截器或异常过滤器时
02

项目结构

将领域代码保留在功能模块内。 将跨切面的过滤器、装饰器、守卫和拦截器放在 common/ 中。 将 DTO 保留在所属模块附近。

SKILL.md · 项目结构
将领域代码保留在功能模块内。将跨切面的过滤器、装饰器、守卫和拦截器放在 common/ 中。将 DTO 保留在所属模块附近。
03

启动与全局验证

始终在公共 API 上启用 whitelist 和 forbidNonWhitelisted。 优先使用一个全局验证管道,而不是为每个路由重复验证配置。

SKILL.md · 启动与全局验证
始终在公共 API 上启用 whitelist 和 forbidNonWhitelisted。优先使用一个全局验证管道,而不是为每个路由重复验证配置。始终在公共 API 上启用 whitelist 和 forbidNonWhitelisted。 优先使用一个全局验证管道,而不是为每个路由重复验证配置。
04

模块、控制器和提供者

控制器应保持精简:解析 HTTP 输入、调用提供者、返回响应 DTO。 将业务逻辑放在可注入的服务中,而不是控制器中。 仅导出其他模块真正需要的提供者。

SKILL.md · 模块、控制器和提供者
控制器应保持精简:解析 HTTP 输入、调用提供者、返回响应 DTO。将业务逻辑放在可注入的服务中,而不是控制器中。仅导出其他模块真正需要的提供者。
05

DTO 与验证

使用 class-validator 验证每个请求 DTO。 使用专用的响应 DTO 或序列化器,而不是直接返回 ORM 实体。 避免泄露内部字段,如密码哈希、令牌或审计列。

SKILL.md · DTO 与验证
使用 class-validator 验证每个请求 DTO。使用专用的响应 DTO 或序列化器,而不是直接返回 ORM 实体。避免泄露内部字段,如密码哈希、令牌或审计列。

SkillSignal prompt templates

Provide the task, context, and acceptance criteria

These prompts were written by SkillSignal from the source structure; they are not upstream text.

Task-start prompt

Confirm source fit, inputs, and outputs before acting.

Use nestjs-patterns to help me with: [specific task]. Context: [files, data, or background]. Constraints: [environment, scope, and prohibited actions]. Before acting, check the pinned SKILL.md and explain which sections apply, what inputs are still missing, and what you will deliver.

Source-guided execution

Make the Agent explicitly follow the key extracted sections.

Apply the pinned nestjs-patterns source to [task]. Pay particular attention to these source sections: “何时启用”, “项目结构”, “启动与全局验证”, “模块、控制器和提供者”, “DTO 与验证”. Preserve the important decision at each step. Mark facts not covered by the source as “needs confirmation” instead of inventing them. Then verify the result against my acceptance criteria: [criteria].

Result-review prompt

Check omissions, permissions, and source drift before delivery.

Review the current nestjs-patterns result: (1) does it satisfy the original task; (2) were any applicable steps or limits in the pinned SKILL.md missed; (3) did it perform any unauthorized file, command, network, or data action; and (4) which conclusions remain unverified? List issues first, then fix only what the source or user authorization supports.

Output checklist

Verify each item before delivery

The task matches the purpose documented in the SKILL.md.

The source section “何时启用” has been checked.

The source section “项目结构” has been checked.

The source section “启动与全局验证” has been checked.

The source section “模块、控制器和提供者” has been checked.

Inputs, constraints, and acceptance criteria are explicit.

Unverified facts, compatibility, and outcome claims are clearly marked.

Any file, command, network, or data action has been reviewed.

Choose a different workflow

When another Skill is the better fit

FAQ

What does nestjs-patterns do?

适用于模块化 TypeScript 后端的生产级 NestJS 模式。

How do I start using nestjs-patterns?

The catalog detected this source-specific install command: npx skills add https://github.com/affaan-m/ECC --skill "docs/zh-CN/skills/nestjs-patterns". Inspect the command and pinned source before running it.

Which Agent platforms does it declare?

No dedicated Agent platform is declared in the pinned source record.

Repository stars
234,327
Repository forks
35,711
Quality
66/100
Source repository last pushed

Quality breakdown

Based on traceable docs and repository signals; stars are not treated as quality.

66/100
Documentation22/30
Specificity14/25
Maintenance20/20
Trust signals10/25

Compare before choosing

Related Agent Skills and source variants

These links are selected from shared tasks, functions, stacks, platforms, and same-name variants. Compare the source owner, documentation, permissions, and maintenance signals.

nestjs-patterns by affaan-m

NestJS architecture patterns for modules, controllers, providers, DTO validation, guards, interceptors, config, and production-grade TypeScript backends.

nestjs-patterns by affaan-m

NestJS architecture patterns for modules, controllers, providers, DTO validation, guards, interceptors, config, and production-grade TypeScript backends.

nestjs-patterns by affaan-m

日本語翻訳:このファイルは nestjs-patterns 用の日本語翻訳が必要です

ab-testing by coreyhaines31

When the user wants to plan, design, or implement an A/B test or experiment, or build a growth experimentation program. Also use when the user mentions "A/B test," "split test," "experiment," "test this change," "variant copy," "multivariate test," "hypothesis," "should I test this," "which version is better," "test two versions," "statistical significance," "how long should I run this test," "growth experiments," "experiment velocity," "experiment backlog," "ICE score," "experimentation program

churn-prevention by coreyhaines31

When the user wants to reduce churn, build cancellation flows, set up save offers, recover failed payments, or implement retention strategies. Also use when the user mentions 'churn,' 'cancel flow,' 'offboarding,' 'save offer,' 'dunning,' 'failed payment recovery,' 'win-back,' 'retention,' 'exit survey,' 'pause subscription,' 'involuntary churn,' 'people keep canceling,' 'churn rate is too high,' 'how do I keep users,' or 'customers are leaving.' Use this whenever someone is losing subscribers o

View original Skill.mdThis page is parsed directly from the repository SKILL.md without editorial rewriting. Collected: Jul 28, 2026 · about 1 min

NestJS 开发模式

适用于模块化 TypeScript 后端的生产级 NestJS 模式。

何时启用

  • 构建 NestJS API 或服务时
  • 组织模块、控制器和提供者时
  • 添加 DTO 验证、守卫、拦截器或异常过滤器时
  • 配置环境感知设置和数据库集成时
  • 测试 NestJS 单元或 HTTP 端点时

项目结构

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/ or database/
  • 将领域代码保留在功能模块内。
  • 将跨切面的过滤器、装饰器、守卫和拦截器放在 common/ 中。
  • 将 DTO 保留在所属模块附近。

启动与全局验证

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();
  • 始终在公共 API 上启用 whitelistforbidNonWhitelisted
  • 优先使用一个全局验证管道,而不是为每个路由重复验证配置。

模块、控制器和提供者

@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);
  }
}
  • 控制器应保持精简:解析 HTTP 输入、调用提供者、返回响应 DTO。
  • 将业务逻辑放在可注入的服务中,而不是控制器中。
  • 仅导出其他模块真正需要的提供者。

DTO 与验证

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

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

  @IsOptional()
  @IsEnum(UserRole)
  role?: UserRole;
}
  • 使用 class-validator 验证每个请求 DTO。
  • 使用专用的响应 DTO 或序列化器,而不是直接返回 ORM 实体。
  • 避免泄露内部字段,如密码哈希、令牌或审计列。

认证、守卫与请求上下文

@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('admin')
@Get('admin/report')
getAdminReport(@Req() req: AuthenticatedRequest) {
  return this.reportService.getForUser(req.user.id);
}
  • 保持认证策略和守卫的模块局部性,除非它们确实是共享的。
  • 在守卫中编码粗粒度的访问规则,然后在服务中进行资源特定的授权。
  • 对经过认证的请求对象,优先使用显式的请求类型。

异常过滤器与错误格式

@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: 'Internal server error',
    });
  }
}
  • 在整个 API 中保持一致的错误封装格式。
  • 对预期的客户端错误抛出框架异常;集中记录并包装意外的失败。

配置与环境验证

ConfigModule.forRoot({
  isGlobal: true,
  load: [configuration],
  validate: validateEnv,
});
  • 在启动时验证环境变量,而不是在首次请求时惰性验证。
  • 将配置访问限制在类型化辅助函数或配置服务之后。
  • 在配置工厂中拆分开发/预发布/生产关注点,而不是在功能代码中到处分支。

持久化与事务

  • 将仓库/ORM 代码保留在提供者之后,这些提供者使用领域语言进行通信。
  • 对于 Prisma 或 TypeORM,将事务工作流隔离在拥有工作单元的服务中。
  • 不要让控制器直接协调多步写入操作。

测试

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();
  });
});
  • 使用模拟依赖项对提供者进行单元测试。
  • 为守卫、验证管道和异常过滤器添加请求级测试。
  • 在测试中复用与生产环境相同的全局管道/过滤器。

生产默认设置

  • 启用结构化日志和请求关联 ID。
  • 在环境/配置无效时终止,而不是部分启动。
  • 优先使用异步提供者初始化数据库/缓存客户端,并附带显式健康检查。
  • 将后台任务和事件消费者放在自己的模块中,而不是 HTTP 控制器内。
  • 对公共端点明确启用速率限制、认证和审计日志。
Source repo
affaan-m/ECC
Skill path
docs/zh-CN/skills/nestjs-patterns/SKILL.md
Commit SHA
4e973d3eaf92
Repository license
MIT
Data collected