File size: 2,032 Bytes
062a991 | 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 | import { and, desc, eq } from "drizzle-orm";
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { getDb } from "@/db";
import { notifications, users } from "@/db/schema";
import { apiResponseError, readJsonObject, requireSameOrigin, requireUser } from "@/lib/api";
const markReadSchema = z.object({
id: z.string().uuid().optional(),
all: z.boolean().optional(),
});
export async function GET(request: NextRequest) {
try {
const user = await requireUser(request);
const rows = await getDb().select({
notification: notifications,
actor: { id: users.id, name: users.name, username: users.username, avatarUrl: users.avatarUrl },
})
.from(notifications)
.leftJoin(users, eq(users.id, notifications.actorId))
.where(eq(notifications.userId, user.id))
.orderBy(desc(notifications.createdAt))
.limit(50);
return NextResponse.json({
notifications: rows.map((row) => ({ ...row.notification, actor: row.actor })),
unread: rows.filter((row) => !row.notification.readAt).length,
});
} catch (error) {
return apiResponseError(error);
}
}
export async function PATCH(request: NextRequest) {
try {
requireSameOrigin(request);
const user = await requireUser(request);
const payload = markReadSchema.parse(await readJsonObject(request));
const db = getDb();
if (payload.all) {
await db.update(notifications).set({ readAt: new Date() }).where(eq(notifications.userId, user.id));
return NextResponse.json({ ok: true });
}
if (!payload.id) return NextResponse.json({ ok: false }, { status: 400 });
const [notification] = await db.update(notifications).set({ readAt: new Date() })
.where(and(eq(notifications.id, payload.id), eq(notifications.userId, user.id)))
.returning();
if (!notification) return NextResponse.json({ ok: false }, { status: 404 });
return NextResponse.json({ notification });
} catch (error) {
return apiResponseError(error);
}
}
|