Skip to content

Commit c332ee4

Browse files
committed
feat: add comment
1 parent 97d8cd8 commit c332ee4

File tree

4 files changed

+364
-21
lines changed

4 files changed

+364
-21
lines changed

modules/home/home.handler.ts

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,12 @@ import {
66
getPosts,
77
} from "@app/modules/home/home.service.ts";
88

9+
// Add these imports for comment handling
10+
import {
11+
createComment,
12+
getCommentsByPostId,
13+
} from "@app/modules/home/home.service.ts";
14+
915
export default async function homeHandler(req: HttpRequest, ctx: Context) {
1016
const ses = await getSession(req, ctx);
1117
const isLogin = ses?.isLogin;
@@ -128,3 +134,90 @@ export async function deletePostHandler(req: HttpRequest, ctx: Context) {
128134
});
129135
}
130136
}
137+
138+
// Handle comment creation
139+
export async function commentHandler(req: HttpRequest, ctx: Context) {
140+
try {
141+
const body = await req.json();
142+
const { content, postId } = body;
143+
144+
if (!content || typeof content !== "string" || content.trim() === "") {
145+
return new Response(JSON.stringify({ error: "Content is required" }), {
146+
status: 400,
147+
headers: { "Content-Type": "application/json" },
148+
});
149+
}
150+
151+
if (!postId) {
152+
return new Response(JSON.stringify({ error: "Post ID is required" }), {
153+
status: 400,
154+
headers: { "Content-Type": "application/json" },
155+
});
156+
}
157+
158+
// Get the user from session
159+
const ses = await getSession(req, ctx);
160+
if (!ses?.isLogin) {
161+
return new Response(
162+
JSON.stringify({ error: "Login required to comment" }),
163+
{
164+
status: 401,
165+
headers: { "Content-Type": "application/json" },
166+
},
167+
);
168+
}
169+
170+
const username = ses.username || "";
171+
172+
// Create the comment
173+
const comment = await createComment({
174+
content,
175+
postId,
176+
author: username,
177+
});
178+
179+
return new Response(JSON.stringify(comment), {
180+
status: 201,
181+
headers: {
182+
"Content-Type": "application/json",
183+
},
184+
});
185+
} catch (error) {
186+
console.error("Error processing comment request:", error);
187+
return new Response(JSON.stringify({ error: "Invalid request" }), {
188+
status: 400,
189+
headers: { "Content-Type": "application/json" },
190+
});
191+
}
192+
}
193+
194+
// Get comments for a post
195+
export async function getCommentsHandler(req: HttpRequest, _ctx: Context) {
196+
try {
197+
const url = new URL(req.url);
198+
const pathParts = url.pathname.split("/");
199+
const postId = pathParts[pathParts.length - 1];
200+
201+
if (!postId) {
202+
return new Response(JSON.stringify({ error: "Post ID is required" }), {
203+
status: 400,
204+
headers: { "Content-Type": "application/json" },
205+
});
206+
}
207+
208+
const comments = await getCommentsByPostId(postId);
209+
210+
return new Response(JSON.stringify(comments), {
211+
status: 200,
212+
headers: {
213+
"Content-Type": "application/json",
214+
},
215+
});
216+
} catch (error) {
217+
console.error("Error fetching comments:", error);
218+
return new Response(JSON.stringify({ error: "Server error" }), {
219+
status: 500,
220+
headers: { "Content-Type": "application/json" },
221+
});
222+
}
223+
}

modules/home/home.service.ts

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,3 +103,65 @@ export async function deletePostById(id: string): Promise<boolean> {
103103
return false;
104104
}
105105
}
106+
107+
// Comment interface
108+
interface CommentInput {
109+
content: string;
110+
postId: string;
111+
author: string;
112+
}
113+
114+
interface Comment {
115+
id: string;
116+
content: string;
117+
postId: string;
118+
timestamp: string;
119+
author: string;
120+
}
121+
122+
// Create a new comment
123+
export async function createComment(input: CommentInput): Promise<Comment> {
124+
const id = ulid();
125+
const comment: Comment = {
126+
id,
127+
content: input.content,
128+
postId: input.postId,
129+
timestamp: new Date().toISOString(),
130+
author: input.author,
131+
};
132+
133+
const primaryKey = ["comments", id];
134+
console.log("Creating comment with ID:", id);
135+
136+
const atomic = kv.atomic()
137+
.check({ key: primaryKey, versionstamp: null })
138+
.set(primaryKey, comment);
139+
140+
const res = await atomic.commit();
141+
console.log("Comment creation result:", res);
142+
if (!res.ok) throw new Error("Failed to create comment");
143+
144+
return comment;
145+
}
146+
147+
// Get comments for a specific post
148+
export async function getCommentsByPostId(postId: string): Promise<Comment[]> {
149+
console.log("Fetching comments for post:", postId);
150+
const results: Comment[] = [];
151+
152+
const iterator = kv.list<Comment>({ prefix: ["comments"] });
153+
154+
for await (const entry of iterator) {
155+
if (entry.value.postId === postId) {
156+
results.push(entry.value);
157+
}
158+
}
159+
160+
// Sort comments by timestamp (newest first)
161+
const comments = results.sort((a, b) =>
162+
new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()
163+
);
164+
165+
console.log(`Retrieved ${comments.length} comments for post ${postId}`);
166+
return comments;
167+
}

modules/home/mod.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@ import { Fastro } from "@app/mod.ts";
22
import pageLayout from "@app/modules/home/home.layout.tsx";
33
import pageComponent from "@app/modules/home/home.page.tsx";
44
import pageHandler, {
5+
commentHandler,
56
deletePostHandler,
7+
getCommentsHandler,
68
postHandler,
79
} from "@app/modules/home/home.handler.ts";
810
import postDetailComponent from "@app/modules/home/post.page.tsx";
@@ -33,9 +35,8 @@ export default function (s: Fastro) {
3335
// Add API endpoint for deleting a post
3436
s.delete("/api/post/:id", deletePostHandler);
3537

36-
// Log registered routes after registration
37-
// console.log("Registered pages:", Object.keys(s.getPages()));
38-
// console.log("Registered routes:", Object.keys(s.getRoutes()));
38+
s.post("/api/comment", commentHandler);
39+
s.get("/api/comments/:id", getCommentsHandler);
3940

4041
return s;
4142
}

0 commit comments

Comments
 (0)