feat : comment feature
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import * as z from "zod";
|
||||
import { getDb } from "@/db";
|
||||
import { commentPushSubscriptions } from "@/db/schema";
|
||||
import { pushPublicKey, validPushEndpoint } from "@/lib/commission/push";
|
||||
import { requireCommentViewer } from "@/lib/comments/repository";
|
||||
import { errorResponse, HttpError, readJson, requireSameOrigin } from "@/lib/security/http";
|
||||
import { limitRequest } from "@/lib/security/rate-limit";
|
||||
|
||||
const subscriptionSchema = z.object({
|
||||
endpoint: z.string().max(2048),
|
||||
keys: z.object({ p256dh: z.string().regex(/^[A-Za-z0-9_-]{50,200}$/), auth: z.string().regex(/^[A-Za-z0-9_-]{10,100}$/) }),
|
||||
});
|
||||
export async function GET() {
|
||||
try {
|
||||
await requireCommentViewer();
|
||||
const publicKey = pushPublicKey();
|
||||
if (!publicKey) throw new HttpError(503, "push-not-configured");
|
||||
return Response.json({ publicKey }, { headers: { "Cache-Control": "private, no-store" } });
|
||||
} catch (cause) { return errorResponse(cause); }
|
||||
}
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
requireSameOrigin(request);
|
||||
const viewer = await requireCommentViewer();
|
||||
if (!pushPublicKey()) throw new HttpError(503, "push-not-configured");
|
||||
await limitRequest("comment-push-subscription", viewer.id, 60);
|
||||
const parsed = subscriptionSchema.safeParse(await readJson(request, 4096));
|
||||
if (!parsed.success || !validPushEndpoint(parsed.data.endpoint)) throw new HttpError(400, "invalid-push-subscription");
|
||||
const { endpoint, keys } = parsed.data;
|
||||
await getDb().insert(commentPushSubscriptions).values({ endpoint, userId: viewer.id, ...keys })
|
||||
.onConflictDoUpdate({ target: commentPushSubscriptions.endpoint, set: { userId: viewer.id, ...keys } });
|
||||
return new Response(null, { status: 204 });
|
||||
} catch (cause) { return errorResponse(cause); }
|
||||
}
|
||||
export async function DELETE(request: Request) {
|
||||
try {
|
||||
requireSameOrigin(request);
|
||||
const viewer = await requireCommentViewer();
|
||||
const parsed = z.object({ endpoint: z.string().max(2048) }).safeParse(await readJson(request, 4096));
|
||||
if (!parsed.success) throw new HttpError(400, "invalid-push-subscription");
|
||||
await getDb().delete(commentPushSubscriptions).where(and(eq(commentPushSubscriptions.endpoint, parsed.data.endpoint), eq(commentPushSubscriptions.userId, viewer.id)));
|
||||
return new Response(null, { status: 204 });
|
||||
} catch (cause) { return errorResponse(cause); }
|
||||
}
|
||||
Reference in New Issue
Block a user