-
-
Notifications
You must be signed in to change notification settings - Fork 170
Expand file tree
/
Copy pathnotification.ts
More file actions
105 lines (93 loc) · 2.97 KB
/
notification.ts
File metadata and controls
105 lines (93 loc) · 2.97 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import { TRPCError } from "@trpc/server";
import { createTRPCRouter, protectedProcedure } from "../trpc";
import {
GetNotificationsSchema,
DeleteNotificationSchema,
} from "../../../schema/notification";
import { notification } from "@/server/db/schema";
import { and, count, desc, eq, inArray, isNotNull } from "drizzle-orm";
export const notificationRouter = createTRPCRouter({
delete: protectedProcedure
.input(DeleteNotificationSchema)
.mutation(async ({ input, ctx }) => {
const { id } = input;
const [currentNotification] = await ctx.db
.select()
.from(notification)
.where(eq(notification.id, id));
if (currentNotification?.userId !== ctx.session.user.id) {
throw new TRPCError({
code: "FORBIDDEN",
});
}
const [notificationRes] = await ctx.db
.delete(notification)
.where(eq(notification.id, id))
.returning();
return notificationRes.id;
}),
deleteAll: protectedProcedure.mutation(async ({ ctx }) => {
const notificationRes = await ctx.db
.delete(notification)
.where(eq(notification.userId, ctx.session.user.id))
.returning();
return notificationRes.length;
}),
get: protectedProcedure
.input(GetNotificationsSchema)
.query(async ({ ctx, input }) => {
const userId = ctx?.session?.user?.id;
const limit = input?.limit ?? 50;
const { cursor } = input;
const response = await ctx.db.query.notification.findMany({
columns: { id: true, type: true, createdAt: true },
with: {
notifier: {
columns: {
name: true,
username: true,
image: true,
},
},
post: {
columns: {
title: true,
slug: true,
},
},
},
where: (notifications, { eq, and, lte }) =>
and(
eq(notifications.userId, userId),
inArray(notifications.type, [0, 1]),
isNotNull(notifications.postId),
isNotNull(notifications.notifierId),
cursor ? lte(notifications.id, cursor) : undefined,
),
limit: limit + 1,
offset: cursor ? 1 : 0,
orderBy: [desc(notification.createdAt)],
});
let nextCursor: typeof cursor | undefined = undefined;
if (response.length > limit) {
const nextItem = response.pop();
nextCursor = nextItem?.id;
}
return { data: response, nextCursor };
}),
getCount: protectedProcedure.query(async ({ ctx }) => {
const userId = ctx?.session?.user?.id;
const [notificationRes] = await ctx.db
.select({ count: count() })
.from(notification)
.where(
and(
eq(notification.userId, userId),
inArray(notification.type, [0, 1]),
isNotNull(notification.postId),
isNotNull(notification.notifierId),
),
);
return notificationRes.count;
}),
});