-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathscript.ts
98 lines (86 loc) · 2.4 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
94
95
96
97
98
import { Prisma, PrismaClient, TaskStatus } from "@prisma/client";
function bypassRLS() {
return Prisma.defineExtension((prisma) =>
prisma.$extends({
query: {
$allModels: {
async $allOperations({ args, query }) {
const [, result] = await prisma.$transaction([
prisma.$executeRaw`SELECT set_config('app.bypass_rls', 'on', TRUE)`,
query(args),
]);
return result;
},
},
},
})
);
}
function forCompany(companyId: string) {
return Prisma.defineExtension((prisma) =>
prisma.$extends({
query: {
$allModels: {
async $allOperations({ args, query }) {
const [, result] = await prisma.$transaction([
prisma.$executeRaw`SELECT set_config('app.current_company_id', ${companyId}, TRUE)`,
query(args),
]);
return result;
},
},
},
})
);
}
const prisma = new PrismaClient();
async function main() {
const user = await prisma.$extends(bypassRLS()).user.findFirstOrThrow();
const companyPrisma = prisma.$extends(forCompany(user.companyId));
const projectInclude = {
owner: true,
tasks: {
include: {
assignee: true,
},
},
} satisfies Prisma.ProjectInclude;
const projects = await companyPrisma.project.findMany({
include: projectInclude,
});
invariant(projects.every((project) => project.companyId === user.companyId));
const newProject = await companyPrisma.project.create({
include: projectInclude,
data: {
title: "New project",
owner: {
connect: { id: user.id },
},
tasks: {
createMany: {
data: [
{ title: "Task A", status: TaskStatus.Pending, userId: user.id },
{ title: "Task B", status: TaskStatus.Pending, userId: user.id },
{ title: "Task C", status: TaskStatus.Pending, userId: user.id },
],
},
},
},
});
invariant(newProject.companyId === user.companyId);
invariant(
newProject.tasks.every((task) => task.companyId === user.companyId)
);
}
function invariant<T>(condition: T): asserts condition {
if (!condition) throw new Error("Invariant failed");
}
main()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});