-
Notifications
You must be signed in to change notification settings - Fork 16
/
delegate.ts
208 lines (188 loc) · 6.82 KB
/
delegate.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import type { Circus } from "@jest/types";
import type { JestEnvironmentConfig, EnvironmentContext } from "@jest/environment";
import chalk from "chalk";
import type { JestEnvironment } from "@jest/environment";
import { PrismaClient, Prisma } from "@prisma/client";
import type { JestPrisma, JestPrismaEnvironmentOptions } from "./types.js";
type PartialEnvironment = Pick<JestEnvironment<unknown>, "handleTestEvent" | "teardown">;
const DEFAULT_MAX_WAIT = 5_000;
const DEFAULT_TIMEOUT = 5_000;
export class PrismaEnvironmentDelegate implements PartialEnvironment {
private prismaClientProxy: PrismaClient | undefined;
private originalClient: PrismaClient;
private triggerTransactionEnd: () => void = () => null;
private readonly options: JestPrismaEnvironmentOptions;
private readonly testPath: string;
private logBuffer: Prisma.QueryEvent[] | undefined = undefined;
getClient() {
return this.prismaClientProxy;
}
constructor(config: JestEnvironmentConfig, context: EnvironmentContext) {
this.options = config.projectConfig.testEnvironmentOptions as JestPrismaEnvironmentOptions;
const originalClient = new PrismaClient({
log: [{ level: "query", emit: "event" }],
...(this.options.databaseUrl && {
datasources: {
db: {
url: this.options.databaseUrl,
},
},
}),
});
originalClient.$on("query", event => {
this.logBuffer?.push(event);
});
this.originalClient = originalClient;
this.testPath = context.testPath.replace(config.globalConfig.rootDir, "").slice(1);
}
async preSetup() {
await this.originalClient.$connect();
const hasInteractiveTransaction = await this.checkInteractiveTransaction();
if (!hasInteractiveTransaction) {
throw new Error(`jest-prisma needs "interactiveTransactions" preview feature.`);
}
const jestPrisma: JestPrisma = {
client: new Proxy<PrismaClient>({} as never, {
get: (_, name: keyof PrismaClient) => {
if (!this.prismaClientProxy) {
console.warn(
"jsetPrisma.client should be used in test or beforeEach functions because transaction has not yet started.",
);
console.warn(
"If you want to access Prisma client in beforeAll or afterAll, use jestPrisma.originalClient.",
);
} else {
return this.prismaClientProxy[name];
}
},
}),
originalClient: this.originalClient,
};
return jestPrisma;
}
handleTestEvent(event: Circus.Event) {
if (event.name === "test_start") {
return this.beginTransaction();
} else if (event.name === "test_done" || event.name === "test_skip") {
return this.endTransaction();
} else if (event.name === "test_fn_start") {
this.logBuffer = [];
} else if (event.name === "test_fn_success" || event.name === "test_fn_failure") {
this.dumpQueryLog(event.test);
this.logBuffer = undefined;
}
}
async teardown() {
await this.originalClient.$disconnect();
}
private async checkInteractiveTransaction() {
const checker: any = () => Promise.resolve(null);
try {
await this.originalClient.$transaction(checker);
return true;
} catch {
return false;
}
}
private async beginTransaction() {
return new Promise<void>(resolve =>
this.originalClient
.$transaction(
transactionClient => {
this.prismaClientProxy = createProxy(transactionClient, this.originalClient, this.options);
resolve();
return new Promise(
(resolve, reject) => (this.triggerTransactionEnd = this.options.disableRollback ? resolve : reject),
);
},
{
maxWait: this.options.maxWait ?? DEFAULT_MAX_WAIT,
timeout: this.options.timeout ?? DEFAULT_TIMEOUT,
},
)
.catch(() => true),
);
}
private async endTransaction() {
this.triggerTransactionEnd();
}
private dumpQueryLog(test: Circus.TestEntry) {
if (this.options.verboseQuery && this.logBuffer) {
let parentBlock: Circus.DescribeBlock | undefined | null = test.parent;
const nameFragments: string[] = [test.name];
while (!!parentBlock) {
nameFragments.push(parentBlock.name);
parentBlock = parentBlock.parent;
}
const breadcrumb = [this.testPath, ...nameFragments.reverse().slice(1)].join(" > ");
console.log(chalk.blue.bold.inverse(" QUERY ") + " " + chalk.gray(breadcrumb));
for (const event of this.logBuffer) {
console.log(`${chalk.blue(" jest-prisma:query")} ${event.query}`);
}
}
}
}
function fakeInnerTransactionFactory(
parentTxClient: Prisma.TransactionClient,
enableExperimentalRollbackInTransaction: boolean,
) {
let seq = 1;
const fakeTransactionMethod = async (
arg: PromiseLike<unknown>[] | ((client: Prisma.TransactionClient) => Promise<unknown>),
) => {
const savePointId = `test_${seq++}`;
if (enableExperimentalRollbackInTransaction) {
await parentTxClient.$executeRawUnsafe(`SAVEPOINT ${savePointId};`);
}
if (Array.isArray(arg)) {
try {
const results = [] as unknown[];
for (const prismaPromise of arg) {
const result = await prismaPromise;
results.push(result);
}
if (enableExperimentalRollbackInTransaction) {
await parentTxClient.$executeRawUnsafe(`RELEASE SAVEPOINT ${savePointId};`);
}
return results;
} catch (err) {
if (enableExperimentalRollbackInTransaction) {
await parentTxClient.$executeRawUnsafe(`ROLLBACK TO SAVEPOINT ${savePointId};`);
}
throw err;
}
} else {
try {
const result = await arg(parentTxClient);
if (enableExperimentalRollbackInTransaction) {
await parentTxClient.$executeRawUnsafe(`RELEASE SAVEPOINT ${savePointId};`);
}
return result;
} catch (err) {
if (enableExperimentalRollbackInTransaction) {
await parentTxClient.$executeRawUnsafe(`ROLLBACK TO SAVEPOINT ${savePointId};`);
}
throw err;
}
}
};
return fakeTransactionMethod;
}
function createProxy(txClient: Prisma.TransactionClient, originalClient: any, options: JestPrismaEnvironmentOptions) {
const boundFakeTransactionMethod = fakeInnerTransactionFactory(
txClient,
options.enableExperimentalRollbackInTransaction ?? false,
);
return new Proxy(txClient, {
get: (target, name) => {
const delegate = target[name as keyof Prisma.TransactionClient];
if (delegate) return delegate;
if (name === "$transaction") {
return boundFakeTransactionMethod;
}
if (originalClient[name as keyof PrismaClient]) {
throw new Error(`Unsupported property: ${name.toString()}`);
}
},
}) as PrismaClient;
}