package v1 import ( "encoding/json" "fmt" "git.mowie.cc/konrad/Library/models" "github.com/labstack/echo" "net/http" "strings" ) type authorPayload struct { Author models.Author `json:"author" form:"author"` } // AuthorAddOrUpdate is the handler to add or update an author func AuthorAddOrUpdate(c echo.Context) error { // Check for Request Content authorFromString := c.FormValue("author") var authorToInsert models.Author if authorFromString == "" { b := new(authorPayload) if err := c.Bind(b); err != nil { fmt.Println(err) return c.JSON(http.StatusBadRequest, models.Message{"No author model provided"}) } authorToInsert = b.Author } else { // Decode the JSON dec := json.NewDecoder(strings.NewReader(authorFromString)) err := dec.Decode(&authorToInsert) if err != nil { return c.JSON(http.StatusInternalServerError, models.Message{"Error decoding author: " + err.Error()}) } } // Check if we have at least a Lastname if authorToInsert.Lastname == "" { return c.JSON(http.StatusBadRequest, models.Message{"Please provide at least a lastame."}) } // Insert the author newAuthor, err := models.AddOrUpdateAuthor(authorToInsert) if err != nil { return c.JSON(http.StatusInternalServerError, models.Message{"Error"}) } return c.JSON(http.StatusOK, newAuthor) }