75 lines
1.8 KiB
Go
75 lines
1.8 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"strconv"
|
|
)
|
|
|
|
func (app *App) handleListDepartments(w http.ResponseWriter, r *http.Request) {
|
|
depts, err := app.listDepartments("")
|
|
if err != nil {
|
|
writeError(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
writeJSON(w, depts)
|
|
}
|
|
|
|
func (app *App) handleCreateDepartment(w http.ResponseWriter, r *http.Request) {
|
|
var d Department
|
|
if err := json.NewDecoder(r.Body).Decode(&d); err != nil {
|
|
writeError(w, "invalid request", http.StatusBadRequest)
|
|
return
|
|
}
|
|
if d.Name == "" {
|
|
writeError(w, "name is required", http.StatusBadRequest)
|
|
return
|
|
}
|
|
if d.Color == "" {
|
|
d.Color = "#6366f1"
|
|
}
|
|
created, err := app.createDepartment(d)
|
|
if err != nil {
|
|
writeError(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusCreated)
|
|
writeJSON(w, created)
|
|
}
|
|
|
|
func (app *App) handleUpdateDepartment(w http.ResponseWriter, r *http.Request) {
|
|
id, err := strconv.Atoi(r.PathValue("id"))
|
|
if err != nil {
|
|
writeError(w, "invalid id", http.StatusBadRequest)
|
|
return
|
|
}
|
|
var d Department
|
|
if err := json.NewDecoder(r.Body).Decode(&d); err != nil {
|
|
writeError(w, "invalid request", http.StatusBadRequest)
|
|
return
|
|
}
|
|
if d.Name == "" {
|
|
writeError(w, "name is required", http.StatusBadRequest)
|
|
return
|
|
}
|
|
d.ID = id
|
|
if err := app.updateDepartment(d); err != nil {
|
|
writeError(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
updated, _ := app.getDepartment(id)
|
|
writeJSON(w, updated)
|
|
}
|
|
|
|
func (app *App) handleDeleteDepartment(w http.ResponseWriter, r *http.Request) {
|
|
id, err := strconv.Atoi(r.PathValue("id"))
|
|
if err != nil {
|
|
writeError(w, "invalid id", http.StatusBadRequest)
|
|
return
|
|
}
|
|
if err := app.deleteDepartment(id); err != nil {
|
|
writeError(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|