Subcategory now accepts POST requests, so they can be added even after a category has been created.

This commit is contained in:
2021-09-09 21:50:44 -05:00
parent f1272b86e8
commit 5cea8df5f5
2 changed files with 60 additions and 0 deletions
+17
View File
@@ -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
}
+43
View File
@@ -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)))
}