72 lines
1.7 KiB
TypeScript
72 lines
1.7 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import { z } from "zod";
|
|
|
|
import prisma from "@/lib/prisma";
|
|
import { getCurrentViewer } from "@/lib/session";
|
|
|
|
const subscriptionSchema = z.object({
|
|
endpoint: z.string().url(),
|
|
keys: z.object({
|
|
p256dh: z.string().min(1),
|
|
auth: z.string().min(1)
|
|
})
|
|
});
|
|
|
|
export async function POST(request: Request) {
|
|
const viewer = await getCurrentViewer();
|
|
|
|
if (!viewer) {
|
|
return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401 });
|
|
}
|
|
|
|
const body = await request.json().catch(() => null);
|
|
const parsed = subscriptionSchema.safeParse(body);
|
|
|
|
if (!parsed.success) {
|
|
return NextResponse.json({ error: "Push-Subscription ist ungültig." }, { status: 400 });
|
|
}
|
|
|
|
await prisma.pushSubscription.upsert({
|
|
where: {
|
|
endpoint: parsed.data.endpoint
|
|
},
|
|
update: {
|
|
userId: viewer.id,
|
|
p256dh: parsed.data.keys.p256dh,
|
|
auth: parsed.data.keys.auth
|
|
},
|
|
create: {
|
|
userId: viewer.id,
|
|
endpoint: parsed.data.endpoint,
|
|
p256dh: parsed.data.keys.p256dh,
|
|
auth: parsed.data.keys.auth
|
|
}
|
|
});
|
|
|
|
return NextResponse.json({ ok: true });
|
|
}
|
|
|
|
export async function DELETE(request: Request) {
|
|
const viewer = await getCurrentViewer();
|
|
|
|
if (!viewer) {
|
|
return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401 });
|
|
}
|
|
|
|
const body = await request.json().catch(() => null);
|
|
const parsed = z.object({ endpoint: z.string().url() }).safeParse(body);
|
|
|
|
if (!parsed.success) {
|
|
return NextResponse.json({ error: "Push-Subscription ist ungültig." }, { status: 400 });
|
|
}
|
|
|
|
await prisma.pushSubscription.deleteMany({
|
|
where: {
|
|
endpoint: parsed.data.endpoint,
|
|
userId: viewer.id
|
|
}
|
|
});
|
|
|
|
return NextResponse.json({ ok: true });
|
|
}
|