-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathscript.ts
93 lines (79 loc) · 2.48 KB
/
script.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
import { Prisma, PrismaClient } from "@prisma/client";
type FlatTransactionClient = Prisma.TransactionClient & {
$commit: () => Promise<void>;
$rollback: () => Promise<void>;
};
const ROLLBACK = { [Symbol.for("prisma.client.extension.rollback")]: true };
const prisma = new PrismaClient({ log: ["query"] }).$extends({
client: {
async $begin() {
const prisma = Prisma.getExtensionContext(this);
let setTxClient: (txClient: Prisma.TransactionClient) => void;
let commit: () => void;
let rollback: () => void;
// a promise for getting the tx inner client
const txClient = new Promise<Prisma.TransactionClient>((res) => {
setTxClient = (txClient) => res(txClient);
});
// a promise for controlling the transaction
const txPromise = new Promise((_res, _rej) => {
commit = () => _res(undefined);
rollback = () => _rej(ROLLBACK);
});
// opening a transaction to control externally
if (
"$transaction" in prisma &&
typeof prisma.$transaction === "function"
) {
const tx = prisma.$transaction((txClient) => {
setTxClient(txClient as unknown as Prisma.TransactionClient);
return txPromise.catch((e) => {
if (e === ROLLBACK) return;
throw e;
});
});
// return a proxy TransactionClient with `$commit` and `$rollback` methods
return new Proxy(await txClient, {
get(target, prop) {
if (prop === "$commit") {
return () => {
commit();
return tx;
};
}
if (prop === "$rollback") {
return () => {
rollback();
return tx;
};
}
return target[prop as keyof typeof target];
},
}) as FlatTransactionClient;
}
throw new Error("Transactions are not supported by this client");
},
},
});
async function main() {
const tx = await prisma.$begin();
const user = await tx.user.findFirstOrThrow();
const tx2 = await prisma.$begin();
await tx2.user.findMany();
await tx.user.update({
where: { id: user.id },
data: { firstName: `${user.firstName} II` },
});
await tx.$commit();
await tx2.user.count();
await tx2.$commit();
}
main()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});