refac: authenticated user can edit an article's body; an unknown id returns 404

This commit is contained in:
fsylvain committed 2026-09-23 23:24:03 +02:00
1 parent 8822bdddd0
commit c16fdbd26d
5 files changed
+425 -9

No files matched your search

+48 -9
View File
@@ -109,6 +109,26 @@ func (h *Handler) PostArticle(w http.ResponseWriter, r *http.Request) {
}
}
func writeArticleErrorResponse(w http.ResponseWriter, err error) {
if errors.Is(err, domain.ErrArticleNotFound) {
http.Error(w, apperr.ArticleNotFoundErrorMessage, http.StatusNotFound)
return
}
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
func writeArticleJsonResponse(w http.ResponseWriter, article domain.Article) {
articleJson, err := json.Marshal(article)
if err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
return
}
if _, err := w.Write(articleJson); err != nil {
log.Printf("Failed to write response: %v", err)
}
}
func (h *Handler) setIsOnline(w http.ResponseWriter, r *http.Request, isOnline bool) {
id, err := parseArticleId(r)
if err != nil {
@@ -118,23 +138,42 @@ func (h *Handler) setIsOnline(w http.ResponseWriter, r *http.Request, isOnline b
updatedArticle, err := h.UpdateUseCase.UpdateIsOnline(id, isOnline)
if err != nil {
if errors.Is(err, domain.ErrArticleNotFound) {
http.Error(w, apperr.ArticleNotFoundErrorMessage, http.StatusNotFound)
return
}
http.Error(w, "Internal server error", http.StatusInternalServerError)
writeArticleErrorResponse(w, err)
return
}
articleJson, err := json.Marshal(updatedArticle)
writeArticleJsonResponse(w, updatedArticle)
}
type UpdateArticleBody struct {
Body string `json:"body" validate:"required,max=10000"`
}
func (h *Handler) UpdateArticleBody(w http.ResponseWriter, r *http.Request) {
id, err := parseArticleId(r)
if err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
return
}
if _, err := w.Write(articleJson); err != nil {
log.Printf("Failed to write response: %v", err)
var localArticle UpdateArticleBody
if err := json.NewDecoder(r.Body).Decode(&localArticle); err != nil {
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
return
}
if err := validator.Validate.Struct(localArticle); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
updatedArticle, err := h.UpdateUseCase.UpdateBody(id, localArticle.Body)
if err != nil {
writeArticleErrorResponse(w, err)
return
}
writeArticleJsonResponse(w, updatedArticle)
}
func (h *Handler) PublishArticle(w http.ResponseWriter, r *http.Request) {