mirror of
https://github.com/wgh136/nysoure.git
synced 2025-09-27 04:17:23 +00:00
Add comment update functionality with UI integration
This commit is contained in:
@@ -14,6 +14,7 @@ func AddCommentRoutes(router fiber.Router) {
|
||||
api.Post("/:resourceID", createComment)
|
||||
api.Get("/:resourceID", listComments)
|
||||
api.Get("/user/:username", listCommentsWithUser)
|
||||
api.Put("/:commentID", updateComment)
|
||||
}
|
||||
|
||||
func createComment(c fiber.Ctx) error {
|
||||
@@ -89,3 +90,28 @@ func listCommentsWithUser(c fiber.Ctx) error {
|
||||
Message: "Comments retrieved successfully",
|
||||
})
|
||||
}
|
||||
|
||||
func updateComment(c fiber.Ctx) error {
|
||||
userID, ok := c.Locals("uid").(uint)
|
||||
if !ok {
|
||||
return model.NewRequestError("You must be logged in to update comment")
|
||||
}
|
||||
commentIDStr := c.Params("commentID")
|
||||
commentID, err := strconv.Atoi(commentIDStr)
|
||||
if err != nil {
|
||||
return model.NewRequestError("Invalid comment ID")
|
||||
}
|
||||
content := c.FormValue("content")
|
||||
if content == "" {
|
||||
return model.NewRequestError("Content cannot be empty")
|
||||
}
|
||||
comment, err := service.UpdateComment(uint(commentID), userID, content)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.JSON(model.Response[model.CommentView]{
|
||||
Success: true,
|
||||
Data: *comment,
|
||||
Message: "Comment updated successfully",
|
||||
})
|
||||
}
|
||||
|
@@ -70,3 +70,16 @@ func GetCommentByID(commentID uint) (*model.Comment, error) {
|
||||
}
|
||||
return &comment, nil
|
||||
}
|
||||
|
||||
func UpdateCommentContent(commentID uint, content string) (*model.Comment, error) {
|
||||
var comment model.Comment
|
||||
if err := db.First(&comment, commentID).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
comment.Content = content
|
||||
if err := db.Save(&comment).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
db.Preload("User").First(&comment, commentID)
|
||||
return &comment, nil
|
||||
}
|
||||
|
@@ -69,3 +69,18 @@ func ListCommentsWithUser(username string, page int) ([]model.CommentWithResourc
|
||||
}
|
||||
return res, totalPages, nil
|
||||
}
|
||||
|
||||
func UpdateComment(commentID, userID uint, content string) (*model.CommentView, error) {
|
||||
comment, err := dao.GetCommentByID(commentID)
|
||||
if err != nil {
|
||||
return nil, model.NewNotFoundError("Comment not found")
|
||||
}
|
||||
if comment.UserID != userID {
|
||||
return nil, model.NewRequestError("You can only update your own comments")
|
||||
}
|
||||
updated, err := dao.UpdateCommentContent(commentID, content)
|
||||
if err != nil {
|
||||
return nil, model.NewInternalServerError("Error updating comment")
|
||||
}
|
||||
return updated.ToView(), nil
|
||||
}
|
||||
|
Reference in New Issue
Block a user