V 0.11.5 : addComment and fields

This commit is contained in:
2025-10-14 22:21:53 +02:00
parent bfb630109f
commit 089f8f3ee8
6 changed files with 159 additions and 29 deletions
@@ -30,7 +30,8 @@
"member",
"admin",
"owner",
"follow"
"follow",
"pending"
]
}
}
+97
View File
@@ -623,5 +623,102 @@ export default factories.createCoreController(
unhiddenPostId: postId,
});
},
/**
* Add a comment to a post
* @param {Object} ctx - The Koa context object
* @returns {Promise<void>} - Sends the created comment as the response
*/
async addComment(ctx) {
const user = ctx.state.user;
if (!user) {
return ctx.unauthorized("You must be logged in to add a comment");
}
const postId = parseInt(String(ctx.params.id));
const { content } = ctx.request.body;
// Validate inputs
if (isNaN(postId)) {
return ctx.badRequest("Invalid post ID");
}
if (!content || typeof content !== "string" || content.trim() === "") {
return ctx.badRequest("Comment content is required");
}
try {
// Step 1: Verify the post exists and get current comments
const currentPost = await strapi.db.query("api::post.post").findOne({
where: { id: postId },
populate: {
comments: {
fields: ["id"],
},
},
});
if (!currentPost) {
return ctx.notFound(`Post with id ${postId} not found`);
}
console.log("=== Current Post Comments ===");
console.log(
"Existing comment IDs:",
currentPost?.comments?.map((c: any) => c.id)
);
// Step 2: Create the new comment in the comments collection
const newComment = await strapi.db
.query("api::comment.comment")
.create({
data: {
content: content.trim(),
owner: user.id,
likes: [],
replies: [],
},
populate: {
owner: {
populate: {
avatar: true,
},
},
},
});
console.log("=== Comment created successfully ===");
console.log("New Comment:", JSON.stringify(newComment, null, 2));
// Step 3: Update the post to include the new comment ID
const existingCommentIds =
currentPost.comments?.map((c: any) => c.id) || [];
await strapi.db.query("api::post.post").update({
where: { id: postId },
data: {
comments: [...existingCommentIds, newComment.id],
},
});
console.log("=== Post updated with new comment ===");
return ctx.send({
message: "Comment added successfully",
comment: newComment,
});
} catch (error: any) {
// Log detailed error if creation fails
console.error("=== STRAPI ERROR DETAILS ===");
console.error("Full error:", JSON.stringify(error, null, 2));
if (error.error?.details?.errors) {
console.error(
"Validation errors:",
JSON.stringify(error.error.details.errors, null, 2)
);
}
return ctx.internalServerError("Failed to add comment");
}
},
})
);
+5
View File
@@ -34,5 +34,10 @@ export default {
path: "/posts/:id/like",
handler: "post.likePost",
},
{
method: "POST",
path: "/posts/:id/comment",
handler: "post.addComment",
},
],
};