Add NestJS Anti-Hallucination Rules#243
Add NestJS Anti-Hallucination Rules#243RolandiPkhakadze wants to merge 1 commit intoPatrickJS:mainfrom
Conversation
📝 WalkthroughWalkthroughA new Cursor rules markdown file was added to define NestJS anti-hallucination guidelines scoped to TypeScript files. The file declares banned import paths, prohibited code patterns, and type/configuration safety constraints to prevent incorrect NestJS implementations during code generation. Changes
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (6)
rules/nestjs-anti-hallucination-cursorrules-prompt-file/.cursorrules.mdc (6)
96-101: Add missing StreamableFile import in the example.The example uses
StreamableFilebut doesn't show the required import statement.📝 Add import for completeness
+// ✅ CORRECT — For file downloads/streaming +import { StreamableFile } from '@nestjs/common'; + // Only use `@Res`() when streaming files or SSE — add { passthrough: true } `@Get`('download') async download(`@Res`({ passthrough: true }) res: Response) { res.set('Content-Type', 'application/octet-stream'); return new StreamableFile(stream); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@rules/nestjs-anti-hallucination-cursorrules-prompt-file/.cursorrules.mdc` around lines 96 - 101, The example uses StreamableFile but lacks its import; update the example to import StreamableFile from Nest (add an import for StreamableFile from '@nestjs/common') so the download method (async download(`@Res`({ passthrough: true }) res: Response) and the StreamableFile usage are complete and compile-ready.
244-248: Note that parameterized query syntax is database-specific.The example shows PostgreSQL-style positional parameters (
$1). Consider noting that the parameter placeholder syntax varies by database:
- PostgreSQL:
$1, $2, ...- MySQL:
?, ?, ...- SQL Server:
@p1,@p2, ...📝 Suggested clarification
// ✅ CORRECT -await this.dataSource.query(`SELECT * FROM users WHERE id = $1`, [userId]); +// PostgreSQL style (adjust syntax for your database): +await this.dataSource.query(`SELECT * FROM users WHERE id = $1`, [userId]); +// Or use QueryBuilder for database-agnostic queries: +await this.userRepo.findOne({ where: { id: userId } });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@rules/nestjs-anti-hallucination-cursorrules-prompt-file/.cursorrules.mdc` around lines 244 - 248, The examples use PostgreSQL-style parameter placeholders ($1) but don't note DB-specific syntax; update the documentation around the this.dataSource.query examples to explicitly state that parameter placeholder syntax varies by database and add the alternative syntaxes (PostgreSQL: $1, $2; MySQL: ? placeholders; SQL Server: `@p1/`@p2) or show multiple example variants for the same query (e.g., SELECT ... WHERE id = $1 with [userId], SELECT ... WHERE id = ? with [userId], and SELECT ... WHERE id = `@p1` with ['@p1': userId]) so readers using different drivers know which placeholder style to use when calling this.dataSource.query.
193-198: Consider adding validation instead of type assertion for external data.Line 197 uses a type assertion (
as PaymentGatewayResponse) for external API data, which doesn't provide runtime type safety. Consider adding a note about runtime validation using class-transformer and class-validator for external data.🛡️ Suggested improvement for external data handling
-const data = await response.json() as PaymentGatewayResponse; +// Better: validate external data at runtime +const rawData = await response.json(); +const data = plainToInstance(PaymentGatewayResponse, rawData); +await validateOrReject(data); + +// Or use a typed schema validator like zod: +const data = PaymentGatewayResponseSchema.parse(await response.json());🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@rules/nestjs-anti-hallucination-cursorrules-prompt-file/.cursorrules.mdc` around lines 193 - 198, Replace the unsafe type assertion on the external response (the line using `await response.json() as PaymentGatewayResponse`) with runtime validation: parse the JSON into a DTO instance (e.g., use class-transformer plainToInstance to create a `PaymentGatewayResponse` object) and run class-validator (or an equivalent schema validator) against it, and if validation fails throw a descriptive error before continuing; update the code that assigns to `data` (and any downstream use of `data`) to rely on the validated DTO instead of the `as PaymentGatewayResponse` assertion.
120-122: Consider clarifying why same-named@Paramand@Queryis problematic.While using both
@Param('id')and@Query('id')with the same name can be confusing, it's not technically invalid - they extract from different parts of the request (path vs query string). Consider clarifying that this is a code smell/maintainability issue rather than a hard error, so developers understand the actual risk (confusion, not runtime failure).💡 Suggested clarification
-// ❌ WRONG — Both `@Param` and `@Query` with same name +// ❌ CONFUSING — Both `@Param` and `@Query` with same name (code smell) `@Get`(':id') -async findOne(`@Param`('id') paramId: string, `@Query`('id') queryId: string) {} +async findOne(`@Param`('id') paramId: string, `@Query`('id') queryId: string) {} +// These extract from different sources but identical names cause confusion🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@rules/nestjs-anti-hallucination-cursorrules-prompt-file/.cursorrules.mdc` around lines 120 - 122, The example using both `@Param`('id') and `@Query`('id') in the findOne method should be updated to clarify this is a maintainability/code‑smell issue (confusing same name across path and query) rather than a runtime error; edit the explanatory text around the snippet referencing `@Param`('id'), `@Query`('id'), and findOne to state they extract from different request locations and recommend remedies (rename one, consolidate sources, or add explicit comments) so readers understand the risk is confusion/bugs, not a compile/runtime failure.
64-79: Add missing Job type import for clarity.The code examples reference
Jobbut don't show its import. For@nestjs/bull, import from'bull'; for@nestjs/bullmq, import from'bullmq'. The API differences shown are accurate—@nestjs/bullmq drops named@Processdecorators in favor of a singleprocess(job: Job)method.📝 Suggested imports for complete examples
For
@nestjs/bullexample, add:import { Job } from 'bull';For
@nestjs/bullmqexample, add:import { Job } from 'bullmq';🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@rules/nestjs-anti-hallucination-cursorrules-prompt-file/.cursorrules.mdc` around lines 64 - 79, The examples reference the Job type but don't import it; update the two snippets to add the proper Job imports: for the `@nestjs/bull` example import Job from 'bull' and for the `@nestjs/bullmq` example import Job from 'bullmq', keeping MyProcessor, `@Process/Processor` and the process(job: Job)/WorkerHost usage unchanged so the examples compile and clearly show the API difference.
13-24: Clarify the distinction between package deprecation and import pattern recommendations.The review's recommendations to use alternatives are sound, but the framing contains inaccuracies regarding deprecation status:
- @nestjs/bull is not deprecated: Both
@nestjs/bulland@nestjs/bullmqare actively maintained in the same monorepo. Bull is in maintenance mode (bug fixes only), while BullMQ is actively developed with new features. Recommending BullMQ for new projects is appropriate, but describing Bull as "legacy" is overstated.- nestjs-redis, nestjs-config, and nestjs-pino are not deprecated: These packages remain active. The recommendations to prefer
@nestjs/config,@nestjs-modules/ioredis, and direct imports fromnestjs-pinorepresent best practices for new projects, not mandatory migrations.- @nestjs/swagger/decorators: The guidance to import directly from
@nestjs/swaggeris correct per official documentation.Update the comment to distinguish between "import paths that don't exist" (the subpaths) versus "packages that are discouraged in favor of better alternatives." The current phrasing may be too strong for packages that remain viable.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@rules/nestjs-anti-hallucination-cursorrules-prompt-file/.cursorrules.mdc` around lines 13 - 24, Update the wording to separate two categories: (1) import subpaths that don't exist or are wrong (e.g., `@nestjs/core/decorators`, `@nestjs/swagger/decorators`, `@nestjs/typeorm/repository`, `@nestjs/passport/strategies`, `@nestjs/bull/decorators`, `@nestjs/cqrs/decorators`) and (2) packages that are discouraged as preferred alternatives rather than deprecated (mention nestjs-redis, nestjs-config, nestjs-pino/logger). Specifically, change the `@nestjs/bull` line to note “maintenance mode (bug fixes only); prefer `@nestjs/bullmq` for new projects” instead of calling it legacy, and rephrase nestjs-redis, nestjs-config, and nestjs-pino/logger lines to “prefer `@nestjs-modules/ioredis` or ioredis, prefer `@nestjs/config`, and prefer importing directly from nestjs-pino” respectively, while preserving the correct guidance to import from `@nestjs/swagger` directly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@rules/nestjs-anti-hallucination-cursorrules-prompt-file/.cursorrules.mdc`:
- Around line 96-101: The example uses StreamableFile but lacks its import;
update the example to import StreamableFile from Nest (add an import for
StreamableFile from '@nestjs/common') so the download method (async
download(`@Res`({ passthrough: true }) res: Response) and the StreamableFile usage
are complete and compile-ready.
- Around line 244-248: The examples use PostgreSQL-style parameter placeholders
($1) but don't note DB-specific syntax; update the documentation around the
this.dataSource.query examples to explicitly state that parameter placeholder
syntax varies by database and add the alternative syntaxes (PostgreSQL: $1, $2;
MySQL: ? placeholders; SQL Server: `@p1/`@p2) or show multiple example variants
for the same query (e.g., SELECT ... WHERE id = $1 with [userId], SELECT ...
WHERE id = ? with [userId], and SELECT ... WHERE id = `@p1` with ['@p1': userId])
so readers using different drivers know which placeholder style to use when
calling this.dataSource.query.
- Around line 193-198: Replace the unsafe type assertion on the external
response (the line using `await response.json() as PaymentGatewayResponse`) with
runtime validation: parse the JSON into a DTO instance (e.g., use
class-transformer plainToInstance to create a `PaymentGatewayResponse` object)
and run class-validator (or an equivalent schema validator) against it, and if
validation fails throw a descriptive error before continuing; update the code
that assigns to `data` (and any downstream use of `data`) to rely on the
validated DTO instead of the `as PaymentGatewayResponse` assertion.
- Around line 120-122: The example using both `@Param`('id') and `@Query`('id') in
the findOne method should be updated to clarify this is a
maintainability/code‑smell issue (confusing same name across path and query)
rather than a runtime error; edit the explanatory text around the snippet
referencing `@Param`('id'), `@Query`('id'), and findOne to state they extract from
different request locations and recommend remedies (rename one, consolidate
sources, or add explicit comments) so readers understand the risk is
confusion/bugs, not a compile/runtime failure.
- Around line 64-79: The examples reference the Job type but don't import it;
update the two snippets to add the proper Job imports: for the `@nestjs/bull`
example import Job from 'bull' and for the `@nestjs/bullmq` example import Job
from 'bullmq', keeping MyProcessor, `@Process/Processor` and the process(job:
Job)/WorkerHost usage unchanged so the examples compile and clearly show the API
difference.
- Around line 13-24: Update the wording to separate two categories: (1) import
subpaths that don't exist or are wrong (e.g., `@nestjs/core/decorators`,
`@nestjs/swagger/decorators`, `@nestjs/typeorm/repository`,
`@nestjs/passport/strategies`, `@nestjs/bull/decorators`, `@nestjs/cqrs/decorators`)
and (2) packages that are discouraged as preferred alternatives rather than
deprecated (mention nestjs-redis, nestjs-config, nestjs-pino/logger).
Specifically, change the `@nestjs/bull` line to note “maintenance mode (bug fixes
only); prefer `@nestjs/bullmq` for new projects” instead of calling it legacy, and
rephrase nestjs-redis, nestjs-config, and nestjs-pino/logger lines to “prefer
`@nestjs-modules/ioredis` or ioredis, prefer `@nestjs/config`, and prefer importing
directly from nestjs-pino” respectively, while preserving the correct guidance
to import from `@nestjs/swagger` directly.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 0c9cd008-8f9e-4395-8981-d0cb931ac569
📒 Files selected for processing (1)
rules/nestjs-anti-hallucination-cursorrules-prompt-file/.cursorrules.mdc
NestJS Anti-Hallucination Rules
Prevents AI from generating common NestJS mistakes:
anytypes and untyped catch blocksCovers @nestjs/bullmq vs deprecated @nestjs/bull, correct class-validator/class-transformer usage, async module factory pitfalls, and wrong decorator combinations.
Summary by CodeRabbit