diff --git a/internal/http/api_handlers.go b/internal/http/api_handlers.go index 1070c46..75891b3 100644 --- a/internal/http/api_handlers.go +++ b/internal/http/api_handlers.go @@ -253,7 +253,54 @@ func (h *MindflowApiHandlers) New(w http.ResponseWriter, r *http.Request) { } func (h *MindflowApiHandlers) Edit(w http.ResponseWriter, r *http.Request) { + var post *mindflow.Post + var err error + + if strings.Contains(r.Header.Get("Content-Type"), "application/x-www-form-urlencoded") { + r.ParseForm() + + body := strings.ReplaceAll(r.FormValue("body"), "\r\n", "\n") + body = strings.ReplaceAll(body, "\n\r", "\n") + body = strings.ReplaceAll(body, "\r", "\n") + + var category mindflow.Category + + if r.FormValue("category") != "" { + category.ID, _ = strconv.ParseInt(r.FormValue("category"), 10, 64) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + if category.ID == 0 { + category.ID, err = h.db.NewCategory(r.FormValue("new-category")) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + } + } else { + category.ID, _ = strconv.ParseInt(r.FormValue("old-category"), 10, 64) + } + + post, err = mindflow.NewPost(category, r.FormValue("title"), body) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + post.ID, _ = strconv.ParseInt(GetURLParam(r, "id"), 10, 64) + } + + if err = h.db.Edit(post); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } } func (h *MindflowApiHandlers) Delete(w http.ResponseWriter, r *http.Request) { + id, _ := strconv.ParseInt(GetURLParam(r, "id"), 10, 64) + if err := h.db.Delete(id); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + } }