chore: improve delete

This commit is contained in:
Andre Henriques 2023-10-06 10:46:45 +01:00
parent 73511ec401
commit 16a6ae844b
4 changed files with 74 additions and 35 deletions

View File

@ -1,7 +1,6 @@
package models package models
import ( import (
"fmt"
"net/http" "net/http"
"os" "os"
"path" "path"
@ -12,26 +11,26 @@ import (
) )
func deleteModel(handle *Handle, id string, w http.ResponseWriter, c *Context, model BaseModel) { func deleteModel(handle *Handle, id string, w http.ResponseWriter, c *Context, model BaseModel) {
fmt.Printf("Removing model with id: %s\n", id) c.Logger.Warnf("Removing model with id: %s", id)
_, err := handle.Db.Exec("delete from models where id=$1;", id) _, err := handle.Db.Exec("delete from models where id=$1;", id)
if err != nil { if err != nil {
fmt.Println(err) c.Logger.Error(err)
panic("TODO handle better deleteModel failed delete database query") panic("TODO handle better deleteModel failed delete database query")
} }
model_path := path.Join("./savedData", id) model_path := path.Join("./savedData", id)
fmt.Printf("Removing folder of model with id: %s at %s\n", id, model_path) c.Logger.Warnf("Removing folder of model with id: %s at %s", id, model_path)
err = os.RemoveAll(model_path) err = os.RemoveAll(model_path)
if err != nil { if err != nil {
fmt.Println(err) c.Logger.Error(err)
panic("TODO handle better deleteModel failed to delete folder") panic("TODO handle better deleteModel failed to delete folder")
} }
if c.Mode == HTML { if c.Mode == HTML {
// TODO move this to a constant so i don't forget // TODO move this to a constant so i don't forget
w.WriteHeader(309) w.WriteHeader(309)
c.Mode = HTMLFULL c.Mode = HTMLFULL
} }
LoadBasedOnAnswer(c.Mode, w, "/models/delete.html", c.AddMap(AnyMap{ LoadBasedOnAnswer(c.Mode, w, "/models/delete.html", c.AddMap(AnyMap{
"Model": model, "Model": model,
@ -44,13 +43,14 @@ func handleDelete(handle *Handle) {
panic("TODO handle json on models/delete") panic("TODO handle json on models/delete")
} }
// This is required to parse delete forms with bodies
f, err := MyParseForm(r) f, err := MyParseForm(r)
if err != nil { if err != nil {
return ErrorCode(err, 400, nil) return c.ErrorCode(err, 400, nil)
} }
if !CheckId(f, "id") { if !CheckId(f, "id") {
return ErrorCode(nil, http.StatusNotFound, AnyMap{ return c.ErrorCode(nil, http.StatusNotFound, AnyMap{
"NotFoundMessage": "Model not found", "NotFoundMessage": "Model not found",
"GoBackLink": "/models", "GoBackLink": "/models",
}) })
@ -61,40 +61,41 @@ func handleDelete(handle *Handle) {
// TODO handle admin users // TODO handle admin users
rows, err := handle.Db.Query("select name, status from models where id=$1 and user_id=$2;", id, c.User.Id) rows, err := handle.Db.Query("select name, status from models where id=$1 and user_id=$2;", id, c.User.Id)
if err != nil { if err != nil {
return Error500(err) return c.ErrorCode(err, http.StatusInternalServerError, nil)
} }
defer rows.Close() defer rows.Close()
if !rows.Next() { if !rows.Next() {
return ErrorCode(nil, http.StatusNotFound, AnyMap{ c.Logger.Warn("Could not find model for", id, c.User.Id)
return c.ErrorCode(nil, http.StatusNotFound, AnyMap{
"NotFoundMessage": "Model not found", "NotFoundMessage": "Model not found",
"GoBackLink": "/models", "GoBackLink": "/models",
}) })
} }
model := BaseModel{} model := BaseModel{}
model.Id = id model.Id = id
err = rows.Scan(&model.Name, &model.Status) if err = rows.Scan(&model.Name, &model.Status); err != nil {
if err != nil { return c.Error500(err)
return Error500(err)
} }
switch model.Status { switch model.Status {
case FAILED_TRAINING: case FAILED_TRAINING:
fallthrough fallthrough
case FAILED_PREPARING_TRAINING: case FAILED_PREPARING_TRAINING:
fallthrough fallthrough
case FAILED_PREPARING: case FAILED_PREPARING:
deleteModel(handle, id, w, c, model) deleteModel(handle, id, w, c, model)
return nil return nil
case READY: case READY:
fallthrough fallthrough
case CONFIRM_PRE_TRAINING: case CONFIRM_PRE_TRAINING:
if CheckEmpty(f, "name") { if CheckEmpty(f, "name") {
// TODO improve result return c.Error400(nil, "Name is empty", w, "/models/edit.html", "delete-model-card", AnyMap{
return ErrorCode(nil, http.StatusBadRequest, nil) "NameDoesNotMatch": true,
"Model": model,
})
} }
name := f.Get("name") name := f.Get("name")

View File

@ -219,14 +219,17 @@ func decodeBody(r *http.Request) (string, *Error) {
} }
func handleError(err *Error, w http.ResponseWriter, context *Context) { func handleError(err *Error, w http.ResponseWriter, context *Context) {
if err != nil { if err != nil {
data := context.AddMap(err.data) data := context.AddMap(err.data)
w.WriteHeader(err.Code)
if err.Code == http.StatusNotFound { if err.Code == http.StatusNotFound {
if context.Mode == HTML {
w.WriteHeader(309)
context.Mode = HTMLFULL
}
LoadBasedOnAnswer(context.Mode, w, "404.html", data) LoadBasedOnAnswer(context.Mode, w, "404.html", data)
return return
} }
w.WriteHeader(err.Code)
if err.Code == http.StatusBadRequest { if err.Code == http.StatusBadRequest {
LoadBasedOnAnswer(context.Mode, w, "400.html", data) LoadBasedOnAnswer(context.Mode, w, "400.html", data)
return return
@ -343,13 +346,48 @@ type Context struct {
Logger *log.Logger Logger *log.Logger
} }
func (c Context) Error400(err error, message string, w http.ResponseWriter, path string, base string, data AnyMap) *Error {
c.SetReportCaller(true)
c.Logger.Error(message)
c.SetReportCaller(false)
if err != nil {
c.Logger.Errorf("Something went wrong returning with: %d\n.Err:\n", http.StatusBadRequest)
c.Logger.Error(err)
}
if c.Mode == JSON {
return &Error{http.StatusBadRequest, nil, c.AddMap(data)}
}
LoadDefineTemplate(w, path, base, c.AddMap(data))
return nil
}
func (c Context) SetReportCaller(report bool) {
if (report) {
c.Logger.SetCallerOffset(2)
c.Logger.SetReportCaller(true)
} else {
c.Logger.SetCallerOffset(1)
c.Logger.SetReportCaller(false)
}
}
func (c Context) ErrorCode(err error, code int, data AnyMap) *Error { func (c Context) ErrorCode(err error, code int, data AnyMap) *Error {
// TODO Improve Logging if (code == 400) {
c.SetReportCaller(true)
c.Logger.Warn("When returning BadRequest(400) please use context.Error400\n")
c.SetReportCaller(false)
}
if err != nil { if err != nil {
c.Logger.Errorf("Something went wrong returning with: %d\n.Err:\n", code) c.Logger.Errorf("Something went wrong returning with: %d\n.Err:\n", code)
c.Logger.Error(err) c.Logger.Error(err)
} }
return &Error{code, nil, data} return &Error{code, nil, c.AddMap(data)}
}
func (c Context) Error500(err error) *Error {
return c.ErrorCode(err, http.StatusInternalServerError, nil)
} }
func (c Context) AddMap(m AnyMap) AnyMap { func (c Context) AddMap(m AnyMap) AnyMap {
@ -516,12 +554,12 @@ func NewHandler(db *sql.DB) *Handle {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Decide answertype // Decide answertype
ans := NORMAL ans := NORMAL
if r.Header.Get("HX-Request") == "true" || r.Header.Get("Request-Type") == "html" {
ans = HTML
}
if r.Header.Get("Request-Type") == "htmlfull" { if r.Header.Get("Request-Type") == "htmlfull" {
ans = HTMLFULL ans = HTMLFULL
} }
if r.Header.Get("Request-Type") == "html" {
ans = HTML
}
//TODO JSON //TODO JSON
//Login state //Login state

View File

@ -30,7 +30,7 @@
Upload image Upload image
</span> </span>
</button> </button>
<input id="file" name="file" type="file" required accept="image/png" /> <input id="file" name="file" type="file" required accept="image/png,image/jpeg" />
</div> </div>
</fieldset> </fieldset>
<button> <button>

View File

@ -353,7 +353,7 @@
</h2> </h2>
<form hx-delete="/models/delete"> <form hx-delete="/models/delete">
<input type="hidden" value="{{ .Model.Id }}" /> <input type="hidden" name="id" value="{{ .Model.Id }}" />
<button class="danger"> <button class="danger">
Delete Delete
</button> </button>