diff --git a/backend/blog.go b/backend/blog.go index 764a1bc..01cf3fd 100644 --- a/backend/blog.go +++ b/backend/blog.go @@ -259,6 +259,27 @@ func (h *ApiHandler) ServeBlogGetSingle(writer http.ResponseWriter, request *htt WriteResponse(writer, http.StatusOK, article) } +func (h *ApiHandler) ServeBlogDelete(writer http.ResponseWriter, request *http.Request) { + idStr := request.PathValue("id") + id, err := strconv.ParseInt(idStr, 10, 64) + if err != nil { + WriteError(writer, http.StatusBadRequest, "invalid id", err) + return + } + + err = h.db.DeleteBlogArticle(id) + if err != nil { + if errors.Is(err, ErrNotFound) { + WriteError(writer, http.StatusNotFound, "article not found", nil) + } else { + WriteError(writer, http.StatusInternalServerError, "failed to update database", err) + } + return + } + + WriteResponse(writer, http.StatusOK, map[string]interface{}{}) +} + func (h *ApiHandler) ServeBlogFileGetSingle(writer http.ResponseWriter, request *http.Request) { idStr := request.PathValue("articleId") articleId, err := strconv.ParseInt(idStr, 10, 64) diff --git a/backend/db.go b/backend/db.go index be189f5..19b0a96 100644 --- a/backend/db.go +++ b/backend/db.go @@ -354,6 +354,43 @@ func (db *Database) SetBlogArticleStatus(id int64, status ArticleStatus) error { return nil } +func (db *Database) DeleteBlogArticle(id int64) error { + tx, err := db.db.Begin() + if err != nil { + return err + } + + _, err = tx.Exec("DELETE FROM blog_file WHERE article_id = ?", id) + if err != nil { + _ = tx.Rollback() + return err + } + + _, err = tx.Exec("DELETE FROM blog_article_to_tag WHERE article_id = ?", id) + if err != nil { + _ = tx.Rollback() + return err + } + + res, err := tx.Exec("DELETE FROM blog_article WHERE id = ?", id) + if err != nil { + _ = tx.Rollback() + return err + } + + affected, err := res.RowsAffected() + if err != nil { + _ = tx.Rollback() + return err + } + if affected == 0 { + _ = tx.Rollback() + return ErrNotFound + } + + return tx.Commit() +} + func (db *Database) GetBlogTags(showAll bool, offset int, limit int) ([]string, int64, error) { filter := "" filterArgs := make([]interface{}, 0) diff --git a/backend/main.go b/backend/main.go index 53cddf4..6f0e153 100644 --- a/backend/main.go +++ b/backend/main.go @@ -41,6 +41,9 @@ func main() { mux.Handle("GET /api/blog/{id}", apiHandler.ProcessAuth(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { apiHandler.ServeBlogGetSingle(writer, request) }), false)) + mux.Handle("DELETE /api/blog/{id}", apiHandler.ProcessAuth(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + apiHandler.ServeBlogDelete(writer, request) + }), true)) mux.Handle("GET /api/blog/{articleId}/file/{fileId}", apiHandler.ProcessAuth(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { apiHandler.ServeBlogFileGetSingle(writer, request) }), false))