59 lines
1.3 KiB
Go
59 lines
1.3 KiB
Go
package main
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
|
|
"github.com/FernandoVideira/LK_API_Temp/internal/store"
|
|
)
|
|
|
|
type CreateCommentPayload struct {
|
|
Content string `json:"content" validate:"required, max=1000"`
|
|
}
|
|
|
|
// CreateComment godoc
|
|
//
|
|
// @Summary Creates a new Comment
|
|
// @Description Creates a new Comment
|
|
// @Tags comments
|
|
// @Accept json
|
|
// @Produce json
|
|
// @Param id path int true "Post ID"
|
|
// @Success 200 {object} store.Comment
|
|
// @Failure 400 {object} error
|
|
// @Failure 404 {object} error
|
|
// @Failure 500 {object} error
|
|
// @Security ApiKeyAuth
|
|
// @Router /posts/{id}/comments [post]
|
|
func (api *api) createCommentHandler(w http.ResponseWriter, r *http.Request) {
|
|
var payload CreateCommentPayload
|
|
if err := readJSON(w, r, &payload); err != nil {
|
|
api.badRequestError(w, r, err)
|
|
return
|
|
}
|
|
|
|
if err := Validate.Struct(payload); err != nil {
|
|
api.badRequestError(w, r, err)
|
|
return
|
|
}
|
|
|
|
post := getPostFromContext(r)
|
|
if post == nil {
|
|
api.notFoundError(w, r, errors.New("post not found"))
|
|
return
|
|
}
|
|
|
|
user := getUserFromContext(r)
|
|
|
|
comment := &store.Comment{
|
|
PostID: post.ID,
|
|
UserID: user.ID,
|
|
Content: payload.Content,
|
|
}
|
|
|
|
if err := api.store.Comments.Create(r.Context(), comment); err != nil {
|
|
api.internalServerError(w, r, err)
|
|
return
|
|
}
|
|
}
|