-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.ts
More file actions
74 lines (66 loc) · 1.72 KB
/
Copy pathscript.ts
File metadata and controls
74 lines (66 loc) · 1.72 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
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
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient({ log: ["query"] });
async function main() {
const users = await getUsersWithPostCounts();
console.info("Users:");
for (const user of users) {
console.info(
` ${user.email} (${user.postsCount} posts, ${user.postsWithCommentsCount} with comments)`
);
}
}
/**
* This function makes 2 total SQL queries:
*
* 1. Get all users, including the number of posts for each user
* 2. Get the number of posts with comments for each user
*
* The second query takes advantage of the fact that Prisma Client has
* a built-in dataloader that automatically batches calls to `findUnique`:
*
* https://www.prisma.io/docs/guides/performance-and-optimization/query-optimization-performance#solving-the-n1-problem
*/
async function getUsersWithPostCounts() {
const users = await prisma.user.findMany({
select: {
id: true,
email: true,
_count: {
select: {
posts: true,
},
},
},
});
return Promise.all(
users.map(async (user) => {
const postsWithCommentsCount = await prisma.user.findUnique({
where: { id: user.id },
select: {
_count: {
select: {
posts: {
where: { comments: { some: {} } },
},
},
},
},
});
return {
id: user.id,
email: user.email,
postsCount: user._count.posts,
postsWithCommentsCount: postsWithCommentsCount?._count.posts,
};
})
);
}
main()
.then(async () => {
await prisma.$disconnect();
})
.catch(async (e) => {
console.error(e);
await prisma.$disconnect();
process.exit(1);
});