From 5cea8df5f53db85fe827f03edd4338e080dc706a Mon Sep 17 00:00:00 2001 From: Garritt McCune Date: Thu, 9 Sep 2021 21:50:44 -0500 Subject: [PATCH] Subcategory now accepts POST requests, so they can be added even after a category has been created. --- category.go | 17 +++++++++++++++++ main.go | 43 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/category.go b/category.go index 5924f9e..464936b 100644 --- a/category.go +++ b/category.go @@ -195,3 +195,20 @@ func getSubcategories(categoryID int64) (subcategories []Subcategory, ok bool) { return subcategories, true } + +func insertSubcategory(name string, categoryID int64) (recordID int64, ok bool) { + db := getSQLConnection() + + defer db.Close() + + err := db.QueryRow("INSERT INTO subcategory(subcategory_name, category_id) VALUES($1, $2) RETURNING subcategory_id;", name, categoryID).Scan(&recordID) + + if err != nil { + //TODO: log this error + println(err.Error()) + return 0, false + //panic(err) + } + + return recordID, true +} diff --git a/main.go b/main.go index 198cb45..e5cb84f 100644 --- a/main.go +++ b/main.go @@ -66,6 +66,8 @@ func category(w http.ResponseWriter, r *http.Request) { func subcategory(w http.ResponseWriter, r *http.Request) { switch r.Method { + case "POST": + insertSubcategoryHandler(w, r) case "DELETE": deleteSubcategoryHandler(w, r) default: @@ -206,3 +208,44 @@ func insertCategoryHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write([]byte(fmt.Sprintf("New Record: %d", id))) } + +func insertSubcategoryHandler(w http.ResponseWriter, r *http.Request) { + ct := r.Header.Get("content-type") + + if ct != "application/json" { + w.WriteHeader(http.StatusUnsupportedMediaType) + w.Write([]byte(fmt.Sprintf("Unsupported media type '%s', expected application/json", ct))) + return + } + + bodyBytes, err := ioutil.ReadAll(r.Body) + + if err != nil { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("Failed to parse request body")) + return + } + + defer r.Body.Close() + + var subcategory Subcategory + + err = json.Unmarshal(bodyBytes, &subcategory) + + if err != nil { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("Failed to unmarshal JSON")) + return + } + + id, ok := insertSubcategory(subcategory.Name, subcategory.CategoryId) + + if !ok { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte("Failed to create the new subcategory.")) + return + } + + w.WriteHeader(http.StatusOK) + w.Write([]byte(fmt.Sprintf("New Record: %d", id))) +}