@nathapp/nestjs-prisma 4.0.0 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/package.json +4 -4
  2. package/.eslintrc.js +0 -8
  3. package/.turbo/turbo-build.log +0 -4
  4. package/CHANGELOG.md +0 -314
  5. package/docs/20260215-fix-plan-prisma.md +0 -37
  6. package/docs/20260215-review-prisma.md +0 -598
  7. package/docs/20260216-plan-prisma-a-minus.md +0 -70
  8. package/lib/errors/prisma-error.mapper.ts +0 -164
  9. package/lib/filter/prisma-exception.filter.ts +0 -67
  10. package/lib/index.ts +0 -12
  11. package/lib/pagination/index.ts +0 -1
  12. package/lib/pagination/paginate.ts +0 -44
  13. package/lib/prisma.constants.ts +0 -40
  14. package/lib/prisma.decorator.ts +0 -8
  15. package/lib/prisma.health.ts +0 -40
  16. package/lib/prisma.interfaces.ts +0 -51
  17. package/lib/prisma.module.ts +0 -281
  18. package/lib/prisma.service.ts +0 -179
  19. package/lib/repository/abstract-prisma.repository.ts +0 -138
  20. package/lib/repository/index.ts +0 -1
  21. package/lib/testing/index.ts +0 -1
  22. package/lib/testing/prisma-testing.utils.ts +0 -29
  23. package/lib/transaction/index.ts +0 -2
  24. package/lib/transaction/prisma-transaction-manager.ts +0 -77
  25. package/lib/transaction/prisma-transaction.constants.ts +0 -29
  26. package/test/error-mapping.spec.ts +0 -231
  27. package/test/jest-nax.json +0 -27
  28. package/test/jest-test.json +0 -29
  29. package/test/lifecycle.spec.ts +0 -241
  30. package/test/multi-db-als.spec.ts +0 -142
  31. package/test/multi-db-transaction.spec.ts +0 -75
  32. package/test/pagination/paginate.spec.ts +0 -359
  33. package/test/prisma-exception-filter.spec.ts +0 -213
  34. package/test/prisma-transaction-manager.spec.ts +0 -285
  35. package/test/prisma.decorator.spec.ts +0 -257
  36. package/test/prisma.health.spec.ts +0 -226
  37. package/test/prisma.module.spec.ts +0 -506
  38. package/test/prisma.service.spec.ts +0 -359
  39. package/test/repository/abstract-prisma.repository.spec.ts +0 -157
  40. package/test/transaction-manager-e2e.spec.ts +0 -496
  41. package/test/transaction.spec.ts +0 -371
  42. package/test/transparent-transaction.spec.ts +0 -500
  43. package/tsconfig.json +0 -9
@@ -1,164 +0,0 @@
1
- import { AppException } from '@nathapp/nestjs-common';
2
- import { PrismaClientKnownRequestError } from '@prisma/client/runtime/library';
3
- import { Logger } from '@nestjs/common';
4
-
5
- /**
6
- * Error code string constants for Prisma errors.
7
- * These string codes are used in error responses for client-side handling.
8
- *
9
- * @property VALUE_TOO_LONG - Value exceeds column length (P2000)
10
- * @property RECORD_NOT_FOUND - Record does not exist (P2001, P2025)
11
- * @property DUPLICATE_ENTRY - Unique constraint violation (P2002)
12
- * @property INVALID_REFERENCE - Foreign key constraint violation (P2003)
13
- * @property RELATION_VIOLATION - Relation constraint violation (P2014)
14
- * @property CONNECTION_TIMEOUT - Database operations timed out (P1008)
15
- * @property DATABASE_ERROR - Generic database error
16
- * @property UNKNOWN_ERROR - Unknown or unexpected error
17
- */
18
- export const PRISMA_ERROR_CODES = {
19
- VALUE_TOO_LONG: 'VALUE_TOO_LONG',
20
- RECORD_NOT_FOUND: 'RECORD_NOT_FOUND',
21
- DUPLICATE_ENTRY: 'DUPLICATE_ENTRY',
22
- INVALID_REFERENCE: 'INVALID_REFERENCE',
23
- RELATION_VIOLATION: 'RELATION_VIOLATION',
24
- CONNECTION_TIMEOUT: 'CONNECTION_TIMEOUT',
25
- DATABASE_ERROR: 'DATABASE_ERROR',
26
- UNKNOWN_ERROR: 'UNKNOWN_ERROR',
27
- } as const;
28
-
29
- /**
30
- * Extended AppException with string code property for Prisma errors.
31
- * Provides both numeric code (for AppException) and string code (for API responses).
32
- */
33
- export class PrismaAppException extends AppException {
34
- public readonly stringCode: string;
35
-
36
- constructor(
37
- numericCode: number,
38
- stringCode: string,
39
- args?: Record<string, unknown>,
40
- httpStatus?: number
41
- ) {
42
- super(numericCode, args, 'prisma', httpStatus);
43
- this.stringCode = stringCode;
44
- }
45
-
46
- /**
47
- * Override code getter to return string code for consistency with test expectations.
48
- */
49
- get code(): any {
50
- return this.stringCode;
51
- }
52
- }
53
-
54
- /**
55
- * Maps Prisma Client errors to standardized PrismaAppException instances.
56
- * Provides consistent error responses across Prisma-based services.
57
- */
58
- export class PrismaErrorMapper {
59
- private static readonly logger = new Logger(PrismaErrorMapper.name);
60
-
61
- /**
62
- * Error code mapping table for Prisma Client Known Request Errors.
63
- * Maps Prisma error codes to HTTP status codes, numeric codes, and string codes.
64
- */
65
- private static readonly ERROR_MAP: Record<
66
- string,
67
- { httpStatus: number; numericCode: number; stringCode: string }
68
- > = {
69
- // P1008: Operations timed out
70
- P1008: { httpStatus: 503, numericCode: 1008, stringCode: PRISMA_ERROR_CODES.CONNECTION_TIMEOUT },
71
-
72
- // P2000: Value too long for column type
73
- P2000: { httpStatus: 400, numericCode: 2000, stringCode: PRISMA_ERROR_CODES.VALUE_TOO_LONG },
74
-
75
- // P2001: Record does not exist in where condition
76
- P2001: { httpStatus: 404, numericCode: 2001, stringCode: PRISMA_ERROR_CODES.RECORD_NOT_FOUND },
77
-
78
- // P2002: Unique constraint violation
79
- P2002: { httpStatus: 409, numericCode: 2002, stringCode: PRISMA_ERROR_CODES.DUPLICATE_ENTRY },
80
-
81
- // P2003: Foreign key constraint violation
82
- P2003: { httpStatus: 400, numericCode: 2003, stringCode: PRISMA_ERROR_CODES.INVALID_REFERENCE },
83
-
84
- // P2014: Relation violation
85
- P2014: { httpStatus: 409, numericCode: 2014, stringCode: PRISMA_ERROR_CODES.RELATION_VIOLATION },
86
-
87
- // P2025: Record not found (for update/delete operations)
88
- P2025: { httpStatus: 404, numericCode: 2025, stringCode: PRISMA_ERROR_CODES.RECORD_NOT_FOUND },
89
- };
90
-
91
- /**
92
- * Maps any error to a PrismaAppException.
93
- *
94
- * @param error - The error to map (Prisma error, generic Error, or null/undefined)
95
- * @returns PrismaAppException with appropriate status code and error code
96
- */
97
- static map(error: any): PrismaAppException {
98
- // Handle null/undefined errors
99
- if (!error) {
100
- return new PrismaAppException(
101
- 9999,
102
- PRISMA_ERROR_CODES.UNKNOWN_ERROR,
103
- { message: 'An unknown error occurred' },
104
- 500
105
- );
106
- }
107
-
108
- // Handle PrismaClientKnownRequestError (instance check or duck-typing)
109
- // Duck-typing check: has 'code' property and optionally 'meta' and 'clientVersion'
110
- const isPrismaError =
111
- error instanceof PrismaClientKnownRequestError ||
112
- (typeof error === 'object' && 'code' in error && typeof error.code === 'string' && error.code.startsWith('P'));
113
-
114
- if (isPrismaError) {
115
- const errorConfig = this.ERROR_MAP[error.code];
116
-
117
- if (errorConfig) {
118
- // P2002 (unique constraint) intentionally exposes only the conflicting field name(s)
119
- // via `meta.target` so callers can produce "X already taken" UX. This is the single
120
- // deliberate exception to the no-raw-meta rule; the full meta is still logged
121
- // server-side only. Note: for some connectors `meta.target` is the constraint/index
122
- // name rather than the logical field — acceptable for this use case.
123
- // For all other known errors, pass no raw meta to avoid leaking DB internals.
124
- const safeArgs: Record<string, unknown> =
125
- error.code === 'P2002' && error.meta?.target
126
- ? { target: error.meta.target }
127
- : {};
128
-
129
- this.logger.error(
130
- `Prisma error ${error.code}: ${error.message}`,
131
- { meta: error.meta, clientVersion: error.clientVersion }
132
- );
133
-
134
- return new PrismaAppException(
135
- errorConfig.numericCode,
136
- errorConfig.stringCode,
137
- safeArgs,
138
- errorConfig.httpStatus
139
- );
140
- }
141
-
142
- // Unknown Prisma error code - log full details server-side, return generic response
143
- this.logger.error(
144
- `Unknown Prisma error ${error.code}: ${error.message}`,
145
- { meta: error.meta }
146
- );
147
- return new PrismaAppException(
148
- 9998,
149
- PRISMA_ERROR_CODES.DATABASE_ERROR,
150
- {},
151
- 500
152
- );
153
- }
154
-
155
- // Handle generic errors - log server-side, return no internal details
156
- this.logger.error('Unexpected database error', { message: error.message || String(error) });
157
- return new PrismaAppException(
158
- 9999,
159
- PRISMA_ERROR_CODES.UNKNOWN_ERROR,
160
- {},
161
- 500
162
- );
163
- }
164
- }
@@ -1,67 +0,0 @@
1
- import { ArgumentsHost, Catch, ExceptionFilter, Logger } from '@nestjs/common';
2
- import {
3
- PrismaClientKnownRequestError,
4
- PrismaClientValidationError
5
- } from '@prisma/client/runtime/library';
6
- import { PrismaErrorMapper, PRISMA_ERROR_CODES } from '../errors/prisma-error.mapper';
7
-
8
- /**
9
- * Global exception filter for Prisma errors.
10
- * Catches PrismaClientKnownRequestError and PrismaClientValidationError and maps them to AppException.
11
- *
12
- * This filter is OPTIONAL - consumers apply it themselves via @UseFilters() or APP_FILTER.
13
- *
14
- * @example
15
- * ```typescript
16
- * // Global application
17
- * app.useGlobalFilters(new PrismaExceptionFilter());
18
- *
19
- * // Controller-level
20
- * @UseFilters(PrismaExceptionFilter)
21
- * @Controller('users')
22
- * export class UsersController {}
23
- *
24
- * // Route-level
25
- * @UseFilters(PrismaExceptionFilter)
26
- * @Get(':id')
27
- * findOne(@Param('id') id: string) {}
28
- * ```
29
- */
30
- @Catch(PrismaClientKnownRequestError, PrismaClientValidationError)
31
- export class PrismaExceptionFilter implements ExceptionFilter {
32
- private readonly logger = new Logger(PrismaExceptionFilter.name);
33
-
34
- catch(exception: PrismaClientKnownRequestError | PrismaClientValidationError, host: ArgumentsHost): void {
35
- const ctx = host.switchToHttp();
36
- const response = ctx.getResponse();
37
-
38
- // Handle PrismaClientValidationError separately
39
- if (exception instanceof PrismaClientValidationError) {
40
- // Log full validation error server-side; never expose raw message in the HTTP response
41
- this.logger.error('PrismaClientValidationError', { message: exception.message });
42
- response.status(400).json({
43
- success: false,
44
- error: {
45
- code: PRISMA_ERROR_CODES.DATABASE_ERROR,
46
- message: 'Invalid query parameters',
47
- args: {},
48
- },
49
- });
50
- return;
51
- }
52
-
53
- // Map Prisma known request error to PrismaAppException
54
- // PrismaErrorMapper.map() already logs full details and strips sensitive data from args
55
- const appException = PrismaErrorMapper.map(exception);
56
-
57
- // Send standardized error response — args contain only safe, sanitized fields
58
- response.status(appException.httpStatus || 500).json({
59
- success: false,
60
- error: {
61
- code: appException.code,
62
- message: 'A database error occurred',
63
- args: appException.args,
64
- },
65
- });
66
- }
67
- }
package/lib/index.ts DELETED
@@ -1,12 +0,0 @@
1
- export * from './prisma.constants';
2
- export * from './prisma.interfaces';
3
- export * from './prisma.module';
4
- export * from './prisma.service';
5
- export * from './prisma.decorator';
6
- export * from './prisma.health';
7
- export * from './pagination';
8
- export * from './testing';
9
- export * from './errors/prisma-error.mapper';
10
- export * from './filter/prisma-exception.filter';
11
- export * from './transaction';
12
- export * from './repository';
@@ -1 +0,0 @@
1
- export * from './paginate';
@@ -1,44 +0,0 @@
1
- import { Page, resolvePageOption } from '@nathapp/nestjs-common';
2
- import type { IPageOption } from '@nathapp/nestjs-common';
3
-
4
- /**
5
- * Paginate a Prisma model query.
6
- *
7
- * @param model - The Prisma model delegate (e.g., prisma.user)
8
- * @param pageOption - Pagination options (current page, page size)
9
- * @param args - Prisma findMany args (where, orderBy, include, select, etc.)
10
- */
11
- export async function Paginate<T>(
12
- model: {
13
- findMany(args?: any): Promise<T[]>;
14
- count(args?: any): Promise<number>;
15
- },
16
- pageOption: IPageOption | any,
17
- args?: {
18
- where?: any;
19
- orderBy?: any;
20
- include?: any;
21
- select?: any;
22
- },
23
- ): Promise<Page<T>> {
24
- const { skip, take } = resolvePageOption(pageOption);
25
-
26
- const findManyArgs: any = {
27
- skip,
28
- take,
29
- };
30
-
31
- if (args) {
32
- if (args.where !== undefined) findManyArgs.where = args.where;
33
- if (args.orderBy !== undefined) findManyArgs.orderBy = args.orderBy;
34
- if (args.include !== undefined) findManyArgs.include = args.include;
35
- if (args.select !== undefined) findManyArgs.select = args.select;
36
- }
37
-
38
- const [records, total] = await Promise.all([
39
- model.findMany(findManyArgs),
40
- model.count({ where: args?.where }),
41
- ]);
42
-
43
- return new Page<T>(pageOption, total, records);
44
- }
@@ -1,40 +0,0 @@
1
- export const DEFAULT_PRISMA_CONNECTION = 'default';
2
- export const PRISMA_MODULE_OPTIONS = Symbol('PRISMA_MODULE_OPTIONS');
3
-
4
- /**
5
- * Get the DI token for a named Prisma connection (the PrismaService).
6
- *
7
- * Single-DB:
8
- * getPrismaToken() → 'PRISMA_SERVICE_DEFAULT'
9
- * getPrismaToken('default') → 'PRISMA_SERVICE_DEFAULT'
10
- *
11
- * Multi-DB:
12
- * getPrismaToken('dbA') → 'PRISMA_SERVICE_dbA'
13
- */
14
- export const getPrismaToken = (name?: string): string =>
15
- name && name !== DEFAULT_PRISMA_CONNECTION
16
- ? `PRISMA_SERVICE_${name}`
17
- : 'PRISMA_SERVICE_DEFAULT';
18
-
19
- /**
20
- * Get the DI token for a named Prisma connection's ITransactionManager.
21
- *
22
- * Pair this with `getPrismaToken(name)` — same logical name, two derived tokens:
23
- *
24
- * getPrismaToken('dbA') → 'PRISMA_SERVICE_dbA'
25
- * getPrismaTransactionManagerToken('dbA') → 'PRISMA_TRANSACTION_MANAGER_dbA'
26
- *
27
- * For the default connection, the module also registers the global
28
- * `TRANSACTION_MANAGER` symbol from `@nathapp/nestjs-data` as an alias, so
29
- * single-DB consumers can keep using `@Inject(TRANSACTION_MANAGER)`.
30
- *
31
- * IMPORTANT — atomicity boundary:
32
- * `tx.run()` on a named tx manager covers ONLY that connection's writes. Writes
33
- * to a different connection from inside that callback are independent and will
34
- * not roll back together. Cross-DB consistency requires sagas/outbox patterns,
35
- * NOT this token. There is no distributed transaction support.
36
- */
37
- export const getPrismaTransactionManagerToken = (name?: string): string =>
38
- name && name !== DEFAULT_PRISMA_CONNECTION
39
- ? `PRISMA_TRANSACTION_MANAGER_${name}`
40
- : 'PRISMA_TRANSACTION_MANAGER_DEFAULT';
@@ -1,8 +0,0 @@
1
- import { Inject } from '@nestjs/common';
2
- import { getPrismaToken } from './prisma.constants';
3
-
4
- /**
5
- * Inject a named PrismaService.
6
- * @param name - Connection name. Default: 'default'
7
- */
8
- export const InjectPrisma = (name?: string) => Inject(getPrismaToken(name));
@@ -1,40 +0,0 @@
1
- import { Injectable } from '@nestjs/common';
2
- import type { PrismaService } from './prisma.service';
3
-
4
- export interface HealthCheckResult {
5
- status: 'up' | 'down';
6
- message?: string;
7
- }
8
-
9
- @Injectable()
10
- export class PrismaHealthIndicator {
11
- constructor(private readonly prismaService: PrismaService) {}
12
-
13
- async isHealthy(): Promise<HealthCheckResult> {
14
- try {
15
- const client = this.prismaService.client as any;
16
-
17
- // If $queryRaw is available, use it to verify connectivity
18
- if (client.$queryRaw) {
19
- // But first check isConnected as a quick filter
20
- if (!this.prismaService.isConnected) {
21
- return { status: 'down', message: 'Not connected' };
22
- }
23
- await client.$queryRaw`SELECT 1`;
24
- return { status: 'up' };
25
- }
26
-
27
- // Fallback: check isConnected when $queryRaw is not available
28
- if (this.prismaService.isConnected) {
29
- return { status: 'up' };
30
- }
31
-
32
- return { status: 'down', message: 'Not connected' };
33
- } catch (error) {
34
- const message = error && typeof error === 'object' && 'message' in error
35
- ? String(error.message)
36
- : 'Health check failed';
37
- return { status: 'down', message };
38
- }
39
- }
40
- }
@@ -1,51 +0,0 @@
1
- import type { ModuleMetadata, Type } from '@nestjs/common';
2
-
3
- /**
4
- * Minimal interface that any PrismaClient must satisfy.
5
- * Works with Prisma 6+ generated clients.
6
- */
7
- export interface PrismaClientLike {
8
- $connect(): Promise<void>;
9
- $disconnect(): Promise<void>;
10
- $on?(event: string, listener: (...args: any[]) => void): void;
11
- $off?(event: string, listener: (...args: any[]) => void): void;
12
- }
13
-
14
- export interface PrismaModuleOptions {
15
- /** Connection name for multi-database. Default: 'default' */
16
- name?: string;
17
-
18
- /** The PrismaClient class (generated by Prisma). */
19
- client?: new (options?: any) => PrismaClientLike;
20
-
21
- /** Options passed to the PrismaClient constructor. */
22
- clientOptions?: Record<string, any>;
23
-
24
- /** If true, module is registered globally. Default: true */
25
- isGlobal?: boolean;
26
-
27
- /** Enable logging of Prisma queries. Default: false */
28
- logging?: boolean;
29
-
30
- /**
31
- * Enable transparent transaction support.
32
- * When true, the injected Prisma client is wrapped in a proxy that
33
- * automatically resolves to the transaction client inside `txManager.run()`.
34
- * Also provides TRANSACTION_MANAGER token.
35
- * Default: false
36
- */
37
- transaction?: boolean;
38
- }
39
-
40
- export interface PrismaModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'> {
41
- name?: string;
42
- isGlobal?: boolean;
43
- useFactory?: (...args: any[]) => PrismaModuleOptions | Promise<PrismaModuleOptions>;
44
- inject?: any[];
45
- useClass?: Type<PrismaOptionsFactory>;
46
- useExisting?: Type<PrismaOptionsFactory>;
47
- }
48
-
49
- export interface PrismaOptionsFactory {
50
- createPrismaOptions(): PrismaModuleOptions | Promise<PrismaModuleOptions>;
51
- }