feat : comment feature
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
import { commentHistory, getCommentViewer, listComments, mutateComment, requireCommentViewer } from "@/lib/comments/repository";
|
||||
import { heartSchema, moderationSchema, reactionSchema } from "@/lib/comments/validation";
|
||||
import { errorResponse, HttpError, readJson, requireSameOrigin } from "@/lib/security/http";
|
||||
import { limitRequest } from "@/lib/security/rate-limit";
|
||||
|
||||
type Context = { params: Promise<{ id: string; action: string }> };
|
||||
export async function GET(request: Request, context: Context) {
|
||||
try {
|
||||
const { id, action } = await context.params;
|
||||
const viewer = await getCommentViewer();
|
||||
const cursor = new URL(request.url).searchParams.get("cursor");
|
||||
const result = action === "history" ? await commentHistory(id, viewer, cursor)
|
||||
: action === "replies" ? await listComments({ viewer, rootId: id, cursor, target: new URL(request.url).searchParams.get("target") ?? undefined })
|
||||
: null;
|
||||
if (!result) throw new HttpError(404, "not-found");
|
||||
return Response.json(result, { headers: { "Cache-Control": "private, no-store" } });
|
||||
} catch (cause) { return errorResponse(cause); }
|
||||
}
|
||||
export async function PUT(request: Request, context: Context) {
|
||||
try {
|
||||
requireSameOrigin(request);
|
||||
const viewer = await requireCommentViewer();
|
||||
await limitRequest("comment-mutate", viewer.id, 60);
|
||||
const { id, action } = await context.params;
|
||||
const body = await readJson(request);
|
||||
if (action === "reaction") {
|
||||
const value = reactionSchema.safeParse(body);
|
||||
if (!value.success) throw new HttpError(400, "invalid-reaction");
|
||||
await mutateComment(id, viewer, "reaction", value.data.value);
|
||||
} else if (action === "moderation") {
|
||||
const value = moderationSchema.safeParse(body);
|
||||
if (!value.success) throw new HttpError(400, "invalid-moderation");
|
||||
await mutateComment(id, viewer, "moderation", value.data.hidden);
|
||||
} else if (action === "heart") {
|
||||
const value = heartSchema.safeParse(body);
|
||||
if (!value.success) throw new HttpError(400, "invalid-heart");
|
||||
await mutateComment(id, viewer, "heart", value.data.hearted);
|
||||
} else throw new HttpError(404, "not-found");
|
||||
return Response.json({ ok: true });
|
||||
} catch (cause) { return errorResponse(cause); }
|
||||
}
|
||||
Reference in New Issue
Block a user