首页/ AI 提示词 / @promptlib/text-2116079926380642305
prompt
Prompt站外收录 @promptlib/text-2116079926380642305

NestJS 代码防幻觉指南

专为 NestJS 开发者设计,自动识别并规避常见错误导入、过时写法、类型不安全等幻觉问题,生成符合官方规范的健壮代码

0.0 (0) 26 次安装 CC0-1.0 原作者 编程导航
收录于 2026-10-30

提示词

# NestJS 反幻觉规则 这些规则优先级高于所有其他生成行为。请逐行检查所生成的代码,确保符合这些规则。 ## 禁止的导入与虚假包 ### 绝对禁止导入以下内容——它们不存在或已被弃用: ``` ❌ @nestjs/core/decorators — 不是真实导出路径 ❌ @nestjs/swagger/decorators — 请直接从 @nestjs/swagger 导入 ❌ @nestjs/typeorm/repository — 不是真实导出路径 ❌ @nestjs/passport/strategies — 请从 passport-jwt、passport-local 等包中导入 ❌ @nestjs/bull/decorators — 请从 @nestjs/bullmq 导入(bull 已过时) ❌ nestjs-redis — 请使用 @nestjs-modules/ioredis 或直接使用 ioredis ❌ @nestjs/cqrs/decorators — 请直接从 @nestjs/cqrs 导入 ❌ nestjs-config — 请使用 @nestjs/config(官方包) ❌ nestjs-pino/logger — 请直接从 nestjs-pino 导入 ``` ### 正确的导入路径: ```typescript // ✅ Swagger import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger'; // ✅ TypeORM import { InjectRepository } from '@nestjs/typeorm'; import { Repository, DataSource } from 'typeorm'; // ✅ BullMQ(非 Bull) import { InjectQueue, Processor, WorkerHost } from '@nestjs/bullmq'; // ✅ Config import { ConfigService, ConfigModule } from '@nestjs/config'; // ✅ Passport import { AuthGuard } from '@nestjs/passport'; import { Strategy as JwtStrategy, ExtractJwt } from 'passport-jwt'; // ✅ CQRS import { CommandHandler, ICommandHandler, EventBus } from '@nestjs/cqrs'; ``` ## 已弃用模式 — 绝对禁止生成以下内容 ### 1. 在 Provider 外部调用 getRepository() ```typescript // ❌ 已弃用 — TypeORM 0.3+ 中已移除 const repo = getRepository(User); const user = await getConnection().getRepository(User).find(); // ✅ 正确 — 通过构造函数注入 constructor( @InjectRepository(User) private readonly userRepo: Repository<User>, ) {} ``` ### 2. 使用 @nestjs/bull(应改用 @nestjs/bullmq) ```typescript // ❌ 过时 — 使用 @nestjs/bull 与 @Process 装饰器 import { Process, Processor } from '@nestjs/bull'; @Processor('queue') class MyProcessor { @Process() async handle(job: Job) {} } // ✅ 当前正确 — 使用 @nestjs/bullmq 与 WorkerHost import { Processor, WorkerHost } from '@nestjs/bullmq'; @Processor('queue') class MyProcessor extends WorkerHost { async process(job: Job): Promise<void> {} } ``` ### 3. Express 特定中间件错误 ```typescript // ❌ 错误 — 在 NestJS 中使用 Express 的 req/res 类型 import { Request, Response } from 'express'; @Get() async findAll(@Req() req: Request, @Res() res: Response) { res.json(data); // 绕过了拦截器、序列化及异常过滤器 } // ✅ 正确 — 使用 NestJS 装饰器并返回值 @Get() async findAll(@Query() query: FindAllQueryDto): Promise<UserResponseDto[]> { return this.usersService.findAll(query); } // 仅在流式传输文件或 SSE 时才使用 @Res() — 并需添加 { passthrough: true } @Get('download') async download(@Res({ passthrough: true }) res: Response) { res.set('Content-Type', 'application/octet-stream'); return new StreamableFile(stream); } ``` ### 4. 错误的装饰器组合 ```typescript // ❌ 错误 — 在控制器上使用 @Injectable() @Injectable() @Controller('users') export class UsersController {} // ❌ 错误 — 在服务上使用 @Controller() @Controller() @Injectable() export class UsersService {} // ❌ 错误 — 在 GET 处理器中使用 @Body() @Get() async findAll(@Body() body: any) {} // GET 请求不应携带请求体 // ❌ 错误 — 同时使用同名的 @Param 和 @Query @Get(':id') async findOne(@Param('id') paramId: string, @Query('id') queryId: string) {} ``` ### 5. class-validator / class-transformer 错误 ```typescript // ❌ 错误 — 未在 main.ts 中启用验证(AI 常遗漏此关键步骤) // main.ts 中必须包含: app.useGlobalPipes(new ValidationPipe({ whitelist: true, // 移除未知属性 forbidNonWhitelisted: true, // 遇到未知属性时抛出异常 transform: true, // 自动将请求载荷转换为 DTO 实例 transformOptions: { enableImplicitConversion: true, }, })); // ❌ 错误 — 验证装饰器与类型不匹配 export class CreateUserDto { @IsString() name: string; @IsNumber() age: string; // 类型不匹配!装饰器要求 number,但字段类型为 string } // ✅ 正确 — 类型与装饰器一致 export class CreateUserDto { @IsString() @IsNotEmpty() name: string; @IsInt() @Min(0) age: number; } ``` ### 6. 异步模块陷阱 ```typescript // ❌ 错误 — useFactory 中未声明 async 却执行 await TypeOrmModule.forRootAsync({ useFactory: (config: ConfigService) => ({ type: 'postgres', url: config.get('DATABASE_URL'), // 未 await,且未声明 inject }), }) // ✅ 正确 TypeOrmModule.forRootAsync({ imports: [ConfigModule], inject: [ConfigService], useFactory: async (config: ConfigService) => ({ type: 'postgres', url: config.getOrThrow<string>('DATABASE_URL'), autoLoadEntities: true, synchronize: false, // 生产环境绝对不可设为 true }), }) ``` ## 类型安全规则 ### 绝对禁止生成 `any` ```typescript // ❌ 禁止 catch (error: any) { ... } const data: any = await response.json(); private cache = new Map<string, any>(); // ✅ 必须 catch (error: unknown) { if (error instanceof DomainError) { ... } throw error; } const data = await response.json() as PaymentGatewayResponse; private cache = new Map<string, CachedSession>(); ``` ### 绝对禁止生成未类型化的事件载荷 ```typescript // ❌ 错误 eventBus.emit('order.created', { order }); // ✅ 正确 — 类型化的事件 export class OrderCreatedEvent { constructor( public readonly orderId: string, public readonly userId: string, public readonly totalAmount: number, public readonly occurredAt: Date = new Date(), ) {} } eventBus.emit(new OrderCreatedEvent(order.id, order.userId, order.total)); ``` ## 配置安全性 ### 绝对禁止硬编码以下值: - 数据库连接字符串 - API 密钥或密钥凭证 - 端口号 - 功能开关 - 外部服务 URL ### 必须始终使用 ConfigService 并调用 getOrThrow: ```typescript // ❌ 错误 const port = process.env.PORT || 3000; const dbUrl = process.env.DATABASE_URL; // ✅ 正确 const port = this.configService.getOrThrow<number>('app.port'); const dbUrl = this.configService.getOrThrow<string>('database.url'); ``` ## 数据库安全性 ### 绝对禁止生成: ```typescript // ❌ 生产环境配置中设置 synchronize: true // ❌ 在迁移文件中使用 DROP TABLE 或 TRUNCATE // ❌ 使用非参数化原始 SQL 查询 await this.dataSource.query(`SELECT * FROM users WHERE id = '${userId}'`); // 存在 SQL 注入风险! // ✅ 正确 await this.dataSource.query(`SELECT * FROM users WHERE id = $1`, [userId]); ``` ## 请牢记 - 若不确定某个包是否存在,请勿导入;应先询问或查阅确认。 - 若正在生成一个你在官方文档中未曾见过的 NestJS 模式,请立即停止并重新考虑。 - 若存疑,宁可生成更少但模式正确的代码,也不要生成更多却依赖猜测的代码。

变量使用 {{name}} 声明,复制时保留占位符

评论 0

还没有评论,来抢沙发。