Skip to content

Commit

Permalink
Add api and action for submitting comment
Browse files Browse the repository at this point in the history
  • Loading branch information
marshallku committed Feb 12, 2024
1 parent 4916128 commit 08cf55b
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 2 deletions.
52 changes: 52 additions & 0 deletions apps/blog/app/[category]/[...slug]/action.ts
Original file line number Diff line number Diff line change
@@ -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<State> {
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: "",
};
}
15 changes: 13 additions & 2 deletions apps/blog/src/api/comment/api.ts
Original file line number Diff line number Diff line change
@@ -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<CommentListResponse>(`/comment/list?postSlug=${encodeURIComponent(slug)}`);
return request<CommentListResponse>(`/comment/list?postSlug=${encodeURIComponent(slug)}`, {
next: {
tags: [slug],
},
});
}

export async function postComment(data: Omit<Comment, "_id" | "createdAt" | "byPostAuthor">) {
return request("/comment/create", {
method: "POST",
body: JSON.stringify(data),
});
}

0 comments on commit 08cf55b

Please sign in to comment.