-
Notifications
You must be signed in to change notification settings - Fork 732
/
Copy pathfetch-trackers.ts
59 lines (53 loc) · 1.5 KB
/
fetch-trackers.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
import prisma from "@/utils/prisma";
import type { ThreadTrackerType } from "@/generated/prisma";
import { getDateFilter, type TimeRange } from "./date-filter";
const PAGE_SIZE = 20;
export async function getPaginatedThreadTrackers({
userId,
type,
page,
timeRange = "all",
}: {
userId: string;
type: ThreadTrackerType;
page: number;
timeRange?: TimeRange;
}) {
const skip = (page - 1) * PAGE_SIZE;
const dateFilter = getDateFilter(timeRange);
const [trackers, total] = await Promise.all([
prisma.threadTracker.findMany({
where: {
userId,
resolved: false,
type,
sentAt: dateFilter,
},
orderBy: {
createdAt: "desc",
},
distinct: ["threadId"],
take: PAGE_SIZE,
skip,
}),
dateFilter
? prisma.$queryRaw<[{ count: bigint }]>`
SELECT COUNT(DISTINCT "threadId") as count
FROM "ThreadTracker"
WHERE "userId" = ${userId}
AND "resolved" = false
AND "type" = ${type}::text::"ThreadTrackerType"
AND "sentAt" <= ${dateFilter.lte}
`
: prisma.$queryRaw<[{ count: bigint }]>`
SELECT COUNT(DISTINCT "threadId") as count
FROM "ThreadTracker"
WHERE "userId" = ${userId}
AND "resolved" = false
AND "type" = ${type}::text::"ThreadTrackerType"
`,
]);
const count = Number(total?.[0]?.count);
const totalPages = Math.ceil(count / PAGE_SIZE);
return { trackers, totalPages, count };
}