From 08cf55b32ae90802160a16132b5eae4065d71864 Mon Sep 17 00:00:00 2001 From: Marshall Ku Date: Mon, 12 Feb 2024 13:50:24 +0900 Subject: [PATCH] Add api and action for submitting comment --- apps/blog/app/[category]/[...slug]/action.ts | 52 ++++++++++++++++++++ apps/blog/src/api/comment/api.ts | 15 +++++- 2 files changed, 65 insertions(+), 2 deletions(-) create mode 100644 apps/blog/app/[category]/[...slug]/action.ts diff --git a/apps/blog/app/[category]/[...slug]/action.ts b/apps/blog/app/[category]/[...slug]/action.ts new file mode 100644 index 00000000..6aabd6e9 --- /dev/null +++ b/apps/blog/app/[category]/[...slug]/action.ts @@ -0,0 +1,52 @@ +"use server"; + +import { headers } from "next/headers"; +import { postComment } from "#api"; +import { revalidatePath, revalidateTag } from "next/cache"; + +interface State { + message: string; +} + +export async function submitComment(_: State, formData: FormData): Promise { + const headersList = headers(); + const fullUrl = headersList.get("referer") || ""; + const body = formData.get("body"); + + if (!fullUrl) { + return { + message: "잘못된 경로입니다.", + }; + } + + if (!body || typeof body !== "string" || body.trim() === "") { + return { + message: "내용을 입력해 주세요.", + }; + } + + const korean = /[\u3131-\uD79D]/giu; + + if (!korean.test(body)) { + return { + message: "한글을 입력해 주세요.", + }; + } + + const data = { + name: (formData.get("name") as string) || "익명", + postSlug: decodeURIComponent(new URL(fullUrl).pathname), + password: formData.get("password") as string, + email: formData.get("email") as string, + url: formData.get("url") as string, + body, + parentCommentId: formData.get("parentCommentId") as string, + }; + + await postComment(data); + revalidateTag(data.postSlug); + + return { + message: "", + }; +} diff --git a/apps/blog/src/api/comment/api.ts b/apps/blog/src/api/comment/api.ts index 92e7074a..459f3b04 100644 --- a/apps/blog/src/api/comment/api.ts +++ b/apps/blog/src/api/comment/api.ts @@ -1,6 +1,17 @@ import { request } from "#api/instance"; -import { CommentListResponse } from "./types"; +import { Comment, CommentListResponse } from "./types"; export async function getComments(slug: string) { - return request(`/comment/list?postSlug=${encodeURIComponent(slug)}`); + return request(`/comment/list?postSlug=${encodeURIComponent(slug)}`, { + next: { + tags: [slug], + }, + }); +} + +export async function postComment(data: Omit) { + return request("/comment/create", { + method: "POST", + body: JSON.stringify(data), + }); }