@nathapp/nestjs-prisma 3.0.0-rc.4
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.
- package/.eslintrc.js +8 -0
- package/.turbo/turbo-build.log +4 -0
- package/.turbo/turbo-test.log +43 -0
- package/CHANGELOG.md +38 -0
- package/CLAUDE.md +17 -0
- package/dist/errors/prisma-error.mapper.d.ts +20 -0
- package/dist/errors/prisma-error.mapper.js +53 -0
- package/dist/errors/prisma-error.mapper.js.map +1 -0
- package/dist/filter/prisma-exception.filter.d.ts +5 -0
- package/dist/filter/prisma-exception.filter.js +43 -0
- package/dist/filter/prisma-exception.filter.js.map +1 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +27 -0
- package/dist/index.js.map +1 -0
- package/dist/pagination/index.d.ts +1 -0
- package/dist/pagination/index.js +18 -0
- package/dist/pagination/index.js.map +1 -0
- package/dist/pagination/paginate.d.ts +11 -0
- package/dist/pagination/paginate.js +27 -0
- package/dist/pagination/paginate.js.map +1 -0
- package/dist/prisma.constants.d.ts +3 -0
- package/dist/prisma.constants.js +10 -0
- package/dist/prisma.constants.js.map +1 -0
- package/dist/prisma.decorator.d.ts +1 -0
- package/dist/prisma.decorator.js +8 -0
- package/dist/prisma.decorator.js.map +1 -0
- package/dist/prisma.health.d.ts +10 -0
- package/dist/prisma.health.js +46 -0
- package/dist/prisma.health.js.map +1 -0
- package/dist/prisma.interfaces.d.ts +24 -0
- package/dist/prisma.interfaces.js +3 -0
- package/dist/prisma.interfaces.js.map +1 -0
- package/dist/prisma.module.d.ts +7 -0
- package/dist/prisma.module.js +109 -0
- package/dist/prisma.module.js.map +1 -0
- package/dist/prisma.service.d.ts +17 -0
- package/dist/prisma.service.js +122 -0
- package/dist/prisma.service.js.map +1 -0
- package/dist/testing/index.d.ts +1 -0
- package/dist/testing/index.js +18 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/prisma-testing.utils.d.ts +8 -0
- package/dist/testing/prisma-testing.utils.js +24 -0
- package/dist/testing/prisma-testing.utils.js.map +1 -0
- package/docs/20260215-fix-plan-prisma.md +37 -0
- package/docs/20260215-review-prisma.md +598 -0
- package/docs/20260216-plan-prisma-a-minus.md +70 -0
- package/lib/errors/prisma-error.mapper.ts +140 -0
- package/lib/filter/prisma-exception.filter.ts +62 -0
- package/lib/index.ts +10 -0
- package/lib/pagination/index.ts +1 -0
- package/lib/pagination/paginate.ts +44 -0
- package/lib/prisma.constants.ts +10 -0
- package/lib/prisma.decorator.ts +8 -0
- package/lib/prisma.health.ts +40 -0
- package/lib/prisma.interfaces.ts +41 -0
- package/lib/prisma.module.ts +115 -0
- package/lib/prisma.service.ts +180 -0
- package/lib/testing/index.ts +1 -0
- package/lib/testing/prisma-testing.utils.ts +29 -0
- package/package.json +31 -0
- package/test/error-mapping.spec.ts +192 -0
- package/test/jest-test.json +24 -0
- package/test/lifecycle.spec.ts +241 -0
- package/test/pagination/paginate.spec.ts +359 -0
- package/test/prisma-exception-filter.spec.ts +213 -0
- package/test/prisma.decorator.spec.ts +257 -0
- package/test/prisma.health.spec.ts +226 -0
- package/test/prisma.module.spec.ts +397 -0
- package/test/prisma.service.spec.ts +359 -0
- package/test/transaction.spec.ts +371 -0
- package/tsconfig.json +9 -0
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { AppException } from '@nathapp/nestjs-common';
|
|
2
|
+
import { PrismaClientKnownRequestError } from '@prisma/client/runtime/library';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Error code string constants for Prisma errors.
|
|
6
|
+
* These string codes are used in error responses for client-side handling.
|
|
7
|
+
*
|
|
8
|
+
* @property VALUE_TOO_LONG - Value exceeds column length (P2000)
|
|
9
|
+
* @property RECORD_NOT_FOUND - Record does not exist (P2001, P2025)
|
|
10
|
+
* @property DUPLICATE_ENTRY - Unique constraint violation (P2002)
|
|
11
|
+
* @property INVALID_REFERENCE - Foreign key constraint violation (P2003)
|
|
12
|
+
* @property RELATION_VIOLATION - Relation constraint violation (P2014)
|
|
13
|
+
* @property CONNECTION_TIMEOUT - Database operations timed out (P1008)
|
|
14
|
+
* @property DATABASE_ERROR - Generic database error
|
|
15
|
+
* @property UNKNOWN_ERROR - Unknown or unexpected error
|
|
16
|
+
*/
|
|
17
|
+
export const PRISMA_ERROR_CODES = {
|
|
18
|
+
VALUE_TOO_LONG: 'VALUE_TOO_LONG',
|
|
19
|
+
RECORD_NOT_FOUND: 'RECORD_NOT_FOUND',
|
|
20
|
+
DUPLICATE_ENTRY: 'DUPLICATE_ENTRY',
|
|
21
|
+
INVALID_REFERENCE: 'INVALID_REFERENCE',
|
|
22
|
+
RELATION_VIOLATION: 'RELATION_VIOLATION',
|
|
23
|
+
CONNECTION_TIMEOUT: 'CONNECTION_TIMEOUT',
|
|
24
|
+
DATABASE_ERROR: 'DATABASE_ERROR',
|
|
25
|
+
UNKNOWN_ERROR: 'UNKNOWN_ERROR',
|
|
26
|
+
} as const;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Extended AppException with string code property for Prisma errors.
|
|
30
|
+
* Provides both numeric code (for AppException) and string code (for API responses).
|
|
31
|
+
*/
|
|
32
|
+
export class PrismaAppException extends AppException {
|
|
33
|
+
public readonly stringCode: string;
|
|
34
|
+
|
|
35
|
+
constructor(
|
|
36
|
+
numericCode: number,
|
|
37
|
+
stringCode: string,
|
|
38
|
+
args?: Record<string, unknown>,
|
|
39
|
+
httpStatus?: number
|
|
40
|
+
) {
|
|
41
|
+
super(numericCode, args, 'prisma', httpStatus);
|
|
42
|
+
this.stringCode = stringCode;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Override code getter to return string code for consistency with test expectations.
|
|
47
|
+
*/
|
|
48
|
+
get code(): any {
|
|
49
|
+
return this.stringCode;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Maps Prisma Client errors to standardized PrismaAppException instances.
|
|
55
|
+
* Provides consistent error responses across Prisma-based services.
|
|
56
|
+
*/
|
|
57
|
+
export class PrismaErrorMapper {
|
|
58
|
+
/**
|
|
59
|
+
* Error code mapping table for Prisma Client Known Request Errors.
|
|
60
|
+
* Maps Prisma error codes to HTTP status codes, numeric codes, and string codes.
|
|
61
|
+
*/
|
|
62
|
+
private static readonly ERROR_MAP: Record<
|
|
63
|
+
string,
|
|
64
|
+
{ httpStatus: number; numericCode: number; stringCode: string }
|
|
65
|
+
> = {
|
|
66
|
+
// P1008: Operations timed out
|
|
67
|
+
P1008: { httpStatus: 503, numericCode: 1008, stringCode: PRISMA_ERROR_CODES.CONNECTION_TIMEOUT },
|
|
68
|
+
|
|
69
|
+
// P2000: Value too long for column type
|
|
70
|
+
P2000: { httpStatus: 400, numericCode: 2000, stringCode: PRISMA_ERROR_CODES.VALUE_TOO_LONG },
|
|
71
|
+
|
|
72
|
+
// P2001: Record does not exist in where condition
|
|
73
|
+
P2001: { httpStatus: 404, numericCode: 2001, stringCode: PRISMA_ERROR_CODES.RECORD_NOT_FOUND },
|
|
74
|
+
|
|
75
|
+
// P2002: Unique constraint violation
|
|
76
|
+
P2002: { httpStatus: 409, numericCode: 2002, stringCode: PRISMA_ERROR_CODES.DUPLICATE_ENTRY },
|
|
77
|
+
|
|
78
|
+
// P2003: Foreign key constraint violation
|
|
79
|
+
P2003: { httpStatus: 400, numericCode: 2003, stringCode: PRISMA_ERROR_CODES.INVALID_REFERENCE },
|
|
80
|
+
|
|
81
|
+
// P2014: Relation violation
|
|
82
|
+
P2014: { httpStatus: 409, numericCode: 2014, stringCode: PRISMA_ERROR_CODES.RELATION_VIOLATION },
|
|
83
|
+
|
|
84
|
+
// P2025: Record not found (for update/delete operations)
|
|
85
|
+
P2025: { httpStatus: 404, numericCode: 2025, stringCode: PRISMA_ERROR_CODES.RECORD_NOT_FOUND },
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Maps any error to a PrismaAppException.
|
|
90
|
+
*
|
|
91
|
+
* @param error - The error to map (Prisma error, generic Error, or null/undefined)
|
|
92
|
+
* @returns PrismaAppException with appropriate status code and error code
|
|
93
|
+
*/
|
|
94
|
+
static map(error: any): PrismaAppException {
|
|
95
|
+
// Handle null/undefined errors
|
|
96
|
+
if (!error) {
|
|
97
|
+
return new PrismaAppException(
|
|
98
|
+
9999,
|
|
99
|
+
PRISMA_ERROR_CODES.UNKNOWN_ERROR,
|
|
100
|
+
{ message: 'An unknown error occurred' },
|
|
101
|
+
500
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Handle PrismaClientKnownRequestError (instance check or duck-typing)
|
|
106
|
+
// Duck-typing check: has 'code' property and optionally 'meta' and 'clientVersion'
|
|
107
|
+
const isPrismaError =
|
|
108
|
+
error instanceof PrismaClientKnownRequestError ||
|
|
109
|
+
(typeof error === 'object' && 'code' in error && typeof error.code === 'string' && error.code.startsWith('P'));
|
|
110
|
+
|
|
111
|
+
if (isPrismaError) {
|
|
112
|
+
const errorConfig = this.ERROR_MAP[error.code];
|
|
113
|
+
|
|
114
|
+
if (errorConfig) {
|
|
115
|
+
return new PrismaAppException(
|
|
116
|
+
errorConfig.numericCode,
|
|
117
|
+
errorConfig.stringCode,
|
|
118
|
+
error.meta || {},
|
|
119
|
+
errorConfig.httpStatus
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Unknown Prisma error code - treat as database error
|
|
124
|
+
return new PrismaAppException(
|
|
125
|
+
9998,
|
|
126
|
+
PRISMA_ERROR_CODES.DATABASE_ERROR,
|
|
127
|
+
{ prismaCode: error.code, message: error.message },
|
|
128
|
+
500
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Handle generic errors
|
|
133
|
+
return new PrismaAppException(
|
|
134
|
+
9999,
|
|
135
|
+
PRISMA_ERROR_CODES.UNKNOWN_ERROR,
|
|
136
|
+
{ message: error.message || String(error) },
|
|
137
|
+
500
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { ArgumentsHost, Catch, ExceptionFilter } 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
|
+
catch(exception: PrismaClientKnownRequestError | PrismaClientValidationError, host: ArgumentsHost): void {
|
|
33
|
+
const ctx = host.switchToHttp();
|
|
34
|
+
const response = ctx.getResponse();
|
|
35
|
+
|
|
36
|
+
// Handle PrismaClientValidationError separately
|
|
37
|
+
if (exception instanceof PrismaClientValidationError) {
|
|
38
|
+
response.status(400).json({
|
|
39
|
+
success: false,
|
|
40
|
+
error: {
|
|
41
|
+
code: PRISMA_ERROR_CODES.DATABASE_ERROR,
|
|
42
|
+
message: 'Invalid query parameters',
|
|
43
|
+
args: { message: exception.message },
|
|
44
|
+
},
|
|
45
|
+
});
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Map Prisma known request error to PrismaAppException
|
|
50
|
+
const appException = PrismaErrorMapper.map(exception);
|
|
51
|
+
|
|
52
|
+
// Send standardized error response
|
|
53
|
+
response.status(appException.httpStatus || 500).json({
|
|
54
|
+
success: false,
|
|
55
|
+
error: {
|
|
56
|
+
code: appException.code,
|
|
57
|
+
message: appException.message || 'A database error occurred',
|
|
58
|
+
args: appException.args,
|
|
59
|
+
},
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
}
|
package/lib/index.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
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';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './paginate';
|
|
@@ -0,0 +1,44 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
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.
|
|
6
|
+
*/
|
|
7
|
+
export const getPrismaToken = (name?: string): string =>
|
|
8
|
+
name && name !== DEFAULT_PRISMA_CONNECTION
|
|
9
|
+
? `PRISMA_SERVICE_${name}`
|
|
10
|
+
: 'PRISMA_SERVICE_DEFAULT';
|
|
@@ -0,0 +1,8 @@
|
|
|
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));
|
|
@@ -0,0 +1,40 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
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
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface PrismaModuleOptions {
|
|
14
|
+
/** Connection name for multi-database. Default: 'default' */
|
|
15
|
+
name?: string;
|
|
16
|
+
|
|
17
|
+
/** The PrismaClient class (generated by Prisma). */
|
|
18
|
+
client?: new (options?: any) => PrismaClientLike;
|
|
19
|
+
|
|
20
|
+
/** Options passed to the PrismaClient constructor. */
|
|
21
|
+
clientOptions?: Record<string, any>;
|
|
22
|
+
|
|
23
|
+
/** If true, module is registered globally. Default: true */
|
|
24
|
+
isGlobal?: boolean;
|
|
25
|
+
|
|
26
|
+
/** Enable logging of Prisma queries. Default: false */
|
|
27
|
+
logging?: boolean;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface PrismaModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'> {
|
|
31
|
+
name?: string;
|
|
32
|
+
isGlobal?: boolean;
|
|
33
|
+
useFactory?: (...args: any[]) => PrismaModuleOptions | Promise<PrismaModuleOptions>;
|
|
34
|
+
inject?: any[];
|
|
35
|
+
useClass?: Type<PrismaOptionsFactory>;
|
|
36
|
+
useExisting?: Type<PrismaOptionsFactory>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface PrismaOptionsFactory {
|
|
40
|
+
createPrismaOptions(): PrismaModuleOptions | Promise<PrismaModuleOptions>;
|
|
41
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { DynamicModule, Module, Provider } from '@nestjs/common';
|
|
2
|
+
import type { PrismaModuleOptions, PrismaModuleAsyncOptions, PrismaOptionsFactory } from './prisma.interfaces';
|
|
3
|
+
import { PrismaService } from './prisma.service';
|
|
4
|
+
import { getPrismaToken, PRISMA_MODULE_OPTIONS } from './prisma.constants';
|
|
5
|
+
|
|
6
|
+
@Module({})
|
|
7
|
+
export class PrismaModule {
|
|
8
|
+
static forRoot(options: PrismaModuleOptions): DynamicModule {
|
|
9
|
+
const { isGlobal = true, name } = options;
|
|
10
|
+
const connectionToken = getPrismaToken(name);
|
|
11
|
+
|
|
12
|
+
const prismaServiceProvider: Provider = {
|
|
13
|
+
provide: connectionToken,
|
|
14
|
+
useFactory: () => new PrismaService(options),
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
const providers: Provider[] = [prismaServiceProvider];
|
|
18
|
+
|
|
19
|
+
if (!name || name === 'default') {
|
|
20
|
+
providers.push({
|
|
21
|
+
provide: PrismaService,
|
|
22
|
+
useExisting: connectionToken,
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
return {
|
|
27
|
+
module: PrismaModule,
|
|
28
|
+
global: isGlobal,
|
|
29
|
+
providers,
|
|
30
|
+
exports: providers,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
static forRootAsync(options: PrismaModuleAsyncOptions): DynamicModule {
|
|
35
|
+
const { isGlobal = true, name } = options;
|
|
36
|
+
const connectionToken = getPrismaToken(name);
|
|
37
|
+
|
|
38
|
+
const asyncProviders = this.createAsyncProviders(options, connectionToken);
|
|
39
|
+
|
|
40
|
+
const providers: Provider[] = [...asyncProviders];
|
|
41
|
+
|
|
42
|
+
if (!name || name === 'default') {
|
|
43
|
+
providers.push({
|
|
44
|
+
provide: PrismaService,
|
|
45
|
+
useExisting: connectionToken,
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return {
|
|
50
|
+
module: PrismaModule,
|
|
51
|
+
global: isGlobal,
|
|
52
|
+
imports: options.imports || [],
|
|
53
|
+
providers,
|
|
54
|
+
exports: providers,
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
private static createAsyncProviders(
|
|
59
|
+
options: PrismaModuleAsyncOptions,
|
|
60
|
+
connectionToken: string,
|
|
61
|
+
): Provider[] {
|
|
62
|
+
if (options.useFactory) {
|
|
63
|
+
return [
|
|
64
|
+
{
|
|
65
|
+
provide: PRISMA_MODULE_OPTIONS,
|
|
66
|
+
useFactory: options.useFactory,
|
|
67
|
+
inject: options.inject || [],
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
provide: connectionToken,
|
|
71
|
+
useFactory: (moduleOptions: PrismaModuleOptions) => new PrismaService(moduleOptions),
|
|
72
|
+
inject: [PRISMA_MODULE_OPTIONS],
|
|
73
|
+
},
|
|
74
|
+
];
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (options.useClass) {
|
|
78
|
+
return [
|
|
79
|
+
{
|
|
80
|
+
provide: options.useClass,
|
|
81
|
+
useClass: options.useClass,
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
provide: PRISMA_MODULE_OPTIONS,
|
|
85
|
+
useFactory: async (optionsFactory: PrismaOptionsFactory) =>
|
|
86
|
+
await optionsFactory.createPrismaOptions(),
|
|
87
|
+
inject: [options.useClass],
|
|
88
|
+
},
|
|
89
|
+
{
|
|
90
|
+
provide: connectionToken,
|
|
91
|
+
useFactory: (moduleOptions: PrismaModuleOptions) => new PrismaService(moduleOptions),
|
|
92
|
+
inject: [PRISMA_MODULE_OPTIONS],
|
|
93
|
+
},
|
|
94
|
+
];
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
if (options.useExisting) {
|
|
98
|
+
return [
|
|
99
|
+
{
|
|
100
|
+
provide: PRISMA_MODULE_OPTIONS,
|
|
101
|
+
useFactory: async (optionsFactory: PrismaOptionsFactory) =>
|
|
102
|
+
await optionsFactory.createPrismaOptions(),
|
|
103
|
+
inject: [options.useExisting],
|
|
104
|
+
},
|
|
105
|
+
{
|
|
106
|
+
provide: connectionToken,
|
|
107
|
+
useFactory: (moduleOptions: PrismaModuleOptions) => new PrismaService(moduleOptions),
|
|
108
|
+
inject: [PRISMA_MODULE_OPTIONS],
|
|
109
|
+
},
|
|
110
|
+
];
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
throw new Error('Invalid PrismaModuleAsyncOptions: must provide useFactory, useClass, or useExisting');
|
|
114
|
+
}
|
|
115
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { Injectable, Logger, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
|
|
2
|
+
import type { PrismaClientLike, PrismaModuleOptions } from './prisma.interfaces';
|
|
3
|
+
import { PrismaErrorMapper } from './errors/prisma-error.mapper';
|
|
4
|
+
|
|
5
|
+
@Injectable()
|
|
6
|
+
export class PrismaService<T extends PrismaClientLike = PrismaClientLike>
|
|
7
|
+
implements OnModuleInit, OnModuleDestroy
|
|
8
|
+
{
|
|
9
|
+
private readonly logger = new Logger(PrismaService.name);
|
|
10
|
+
private _client: T;
|
|
11
|
+
private _isConnected = false;
|
|
12
|
+
private readonly connectionName: string;
|
|
13
|
+
private queryListener?: (event: any) => void;
|
|
14
|
+
private isDestroying = false;
|
|
15
|
+
|
|
16
|
+
constructor(private readonly options: PrismaModuleOptions) {
|
|
17
|
+
this.connectionName = options.name || 'default';
|
|
18
|
+
|
|
19
|
+
const ClientClass = options.client;
|
|
20
|
+
if (!ClientClass) {
|
|
21
|
+
throw new Error(
|
|
22
|
+
`PrismaService [${this.connectionName}]: No PrismaClient class provided. ` +
|
|
23
|
+
`Pass the generated PrismaClient class in the 'client' option.`
|
|
24
|
+
);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
this._client = new ClientClass(options.clientOptions) as T;
|
|
28
|
+
|
|
29
|
+
// Store listener reference for proper cleanup
|
|
30
|
+
if (options.logging && this._client.$on) {
|
|
31
|
+
this.queryListener = (event: any) => {
|
|
32
|
+
this.logger.debug(`[${this.connectionName}] Query: ${event.query}`, 'PrismaQuery');
|
|
33
|
+
};
|
|
34
|
+
this._client.$on('query', this.queryListener);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
get client(): T {
|
|
39
|
+
return this._client;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
get isConnected(): boolean {
|
|
43
|
+
return this._isConnected;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async onModuleInit(): Promise<void> {
|
|
47
|
+
try {
|
|
48
|
+
await this._client.$connect();
|
|
49
|
+
this._isConnected = true;
|
|
50
|
+
this.logger.log(`Prisma [${this.connectionName}] connected`);
|
|
51
|
+
} catch (error: any) {
|
|
52
|
+
this.logger.error(
|
|
53
|
+
`Prisma [${this.connectionName}] failed to connect: ${error?.message || String(error)}`,
|
|
54
|
+
error?.stack || '',
|
|
55
|
+
);
|
|
56
|
+
throw error;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async onModuleDestroy(): Promise<void> {
|
|
61
|
+
// Implement idempotent destroy to handle concurrent destroy calls
|
|
62
|
+
if (this.isDestroying) {
|
|
63
|
+
return Promise.resolve();
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
this.isDestroying = true;
|
|
67
|
+
|
|
68
|
+
try {
|
|
69
|
+
// Clean up query event listener before disconnecting
|
|
70
|
+
if (this.queryListener && '$off' in this._client && typeof this._client.$off === 'function') {
|
|
71
|
+
try {
|
|
72
|
+
(this._client as any).$off('query', this.queryListener);
|
|
73
|
+
this.queryListener = undefined;
|
|
74
|
+
} catch (cleanupError: any) {
|
|
75
|
+
// Log cleanup errors but don't throw - continue with disconnect
|
|
76
|
+
this.logger.error(
|
|
77
|
+
`Prisma [${this.connectionName}] failed to clean up query listener: ${cleanupError?.message || String(cleanupError)}`,
|
|
78
|
+
cleanupError?.stack || '',
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Only disconnect if currently connected
|
|
84
|
+
if (this._isConnected) {
|
|
85
|
+
await this._client.$disconnect();
|
|
86
|
+
this._isConnected = false;
|
|
87
|
+
this.logger.log(`Prisma [${this.connectionName}] disconnected`);
|
|
88
|
+
}
|
|
89
|
+
} catch (error: any) {
|
|
90
|
+
this._isConnected = false;
|
|
91
|
+
const errorMessage = error?.message || String(error);
|
|
92
|
+
const errorStack = error?.stack || '';
|
|
93
|
+
this.logger.error(
|
|
94
|
+
`Prisma [${this.connectionName}] failed to disconnect: ${errorMessage}`,
|
|
95
|
+
errorStack,
|
|
96
|
+
);
|
|
97
|
+
} finally {
|
|
98
|
+
this.isDestroying = false;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return Promise.resolve();
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Execute a callback within a Prisma transaction.
|
|
106
|
+
* Provides automatic error mapping to AppException and logging.
|
|
107
|
+
*
|
|
108
|
+
* @param callback - The function to execute within the transaction context
|
|
109
|
+
* @param options - Optional Prisma transaction options (isolationLevel, maxWait, timeout)
|
|
110
|
+
* @returns The result of the callback
|
|
111
|
+
*
|
|
112
|
+
* @example
|
|
113
|
+
* ```typescript
|
|
114
|
+
* const result = await prismaService.withTransaction(async (tx) => {
|
|
115
|
+
* const user = await tx.user.create({ data: { email: 'test@example.com' } });
|
|
116
|
+
* const profile = await tx.profile.create({ data: { userId: user.id } });
|
|
117
|
+
* return { user, profile };
|
|
118
|
+
* });
|
|
119
|
+
* ```
|
|
120
|
+
*/
|
|
121
|
+
async withTransaction<R>(
|
|
122
|
+
callback: (tx: any) => Promise<R>,
|
|
123
|
+
options?: any
|
|
124
|
+
): Promise<R> {
|
|
125
|
+
const client = this._client as any;
|
|
126
|
+
|
|
127
|
+
if (!('$transaction' in client) || typeof client.$transaction !== 'function') {
|
|
128
|
+
throw new Error(
|
|
129
|
+
`PrismaService [${this.connectionName}]: $transaction is not available on this client`
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const startTime = Date.now();
|
|
134
|
+
|
|
135
|
+
if (this.options.logging) {
|
|
136
|
+
this.logger.debug(
|
|
137
|
+
`[${this.connectionName}] Transaction started`,
|
|
138
|
+
'PrismaTransaction'
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
try {
|
|
143
|
+
// Execute the transaction
|
|
144
|
+
const result = await client.$transaction(callback, options);
|
|
145
|
+
|
|
146
|
+
if (this.options.logging) {
|
|
147
|
+
const duration = Date.now() - startTime;
|
|
148
|
+
this.logger.debug(
|
|
149
|
+
`[${this.connectionName}] Transaction committed (${duration}ms)`,
|
|
150
|
+
'PrismaTransaction'
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
return result;
|
|
155
|
+
} catch (error: any) {
|
|
156
|
+
const duration = Date.now() - startTime;
|
|
157
|
+
|
|
158
|
+
if (this.options.logging) {
|
|
159
|
+
this.logger.error(
|
|
160
|
+
`[${this.connectionName}] Transaction rolled back (${duration}ms): ${error?.message || String(error)}`,
|
|
161
|
+
error?.stack || ''
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// Only map Prisma errors to AppException
|
|
166
|
+
// For generic errors, preserve original error to maintain message and stack trace
|
|
167
|
+
const isPrismaError =
|
|
168
|
+
(typeof error === 'object' && error !== null) &&
|
|
169
|
+
('code' in error && typeof error.code === 'string' && error.code.startsWith('P'));
|
|
170
|
+
|
|
171
|
+
if (isPrismaError) {
|
|
172
|
+
const mappedError = PrismaErrorMapper.map(error);
|
|
173
|
+
throw mappedError;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// Re-throw generic errors as-is
|
|
177
|
+
throw error;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './prisma-testing.utils';
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { PrismaClientLike } from '../prisma.interfaces';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Create a mock PrismaClient for testing.
|
|
5
|
+
* All methods return jest mock functions.
|
|
6
|
+
*/
|
|
7
|
+
export function createMockPrismaClient(): PrismaClientLike & Record<string, any> {
|
|
8
|
+
return {
|
|
9
|
+
$connect: jest.fn().mockResolvedValue(undefined),
|
|
10
|
+
$disconnect: jest.fn().mockResolvedValue(undefined),
|
|
11
|
+
$on: jest.fn(),
|
|
12
|
+
$queryRaw: jest.fn(),
|
|
13
|
+
$executeRaw: jest.fn(),
|
|
14
|
+
$transaction: jest.fn(),
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Create a mock PrismaService for testing.
|
|
20
|
+
*/
|
|
21
|
+
export function createMockPrismaService() {
|
|
22
|
+
const mockClient = createMockPrismaClient();
|
|
23
|
+
return {
|
|
24
|
+
client: mockClient,
|
|
25
|
+
isConnected: true,
|
|
26
|
+
onModuleInit: jest.fn().mockResolvedValue(undefined),
|
|
27
|
+
onModuleDestroy: jest.fn().mockResolvedValue(undefined),
|
|
28
|
+
};
|
|
29
|
+
}
|