-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtransaction.ts
More file actions
34 lines (29 loc) · 1.18 KB
/
transaction.ts
File metadata and controls
34 lines (29 loc) · 1.18 KB
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
import { createClient } from './db';
async function main() {
const db = await createClient();
console.log('Create two users with a sequential transaction');
const users = await db.$transaction([
db.user.create({ data: { email: 'u1@test.com' } }),
db.user.create({ data: { email: 'u2@test.com' } })
]);
console.log(users);
console.log('Create two users with unique constraint violation');
try {
await db.$transaction([
db.user.create({ data: { email: 'u3@test.com' } }),
db.user.create({ data: { email: 'u3@test.com' } })
]);
} catch (err: any) {
console.log('Transaction rolled back due to:', err.cause.message);
// the following should log: "User created: null"
console.log('User created:', await db.user.findUnique({ where: { email: 'u3@test.com' } }));
}
console.log('Create user and post with an interactive transaction');
const [user, post] = await db.$transaction(async (tx) => {
const user = await tx.user.create({ data: { email: 'u3@test.com' } });
const post = await tx.post.create({ data: { title: 'Post1', authorId: user.id } });
return [user, post];
});
console.log('Created user and post:', user, post);
}
main();