diff --git a/models/authors_update.go b/models/authors_update.go new file mode 100644 index 0000000..3679e5f --- /dev/null +++ b/models/authors_update.go @@ -0,0 +1,14 @@ +package models + +func UpdateAuthor(author Author, id int64) (newAuthor Author, err error){ + _, err = x.Where("id = ?", id).Update(&author) + + if err != nil { + return Author{}, err + } + + // Get the newly updated author + newAuthor, _, err = GetAuthorByID(id) + + return newAuthor, err +} \ No newline at end of file diff --git a/routes/api/v1/authors_update.go b/routes/api/v1/authors_update.go new file mode 100644 index 0000000..dacfae1 --- /dev/null +++ b/routes/api/v1/authors_update.go @@ -0,0 +1,56 @@ +package v1 + +import ( + "github.com/labstack/echo" + "net/http" + "git.mowie.cc/konrad/Library/models" + "encoding/json" + "strings" + "strconv" +) + +func AuthorUpdate(c echo.Context) error { + // Check for Request Content + author := c.FormValue("author") + if author == "" { + return c.JSON(http.StatusBadRequest, models.Message{"No author model provided"}) + } + + // Look for the authors id + id := c.Param("id") + + // Make int + authorID, err := strconv.ParseInt(id, 10, 64) + + if err != nil { + return c.JSON(http.StatusInternalServerError, models.Message{"Could not get author infos"}) + } + + // Check if the author exists + _, exists, err := models.GetAuthorByID(authorID) + if err != nil { + return c.JSON(http.StatusInternalServerError, models.Message{"Could not get author infos"}) + } + + if !exists { + return c.JSON(http.StatusBadRequest, models.Message{"The author does not exist."}) + } + + // Decode the JSON + var authorstruct models.Author + dec := json.NewDecoder(strings.NewReader(author)) + + err = dec.Decode(&authorstruct) + if err != nil { + return c.JSON(http.StatusInternalServerError, models.Message{"Error decoding author: " + err.Error()}) + } + + // Insert the author + newAuthor, err := models.UpdateAuthor(authorstruct, authorID) + + if err != nil { + return c.JSON(http.StatusInternalServerError, models.Message{"Error"}) + } + + return c.JSON(http.StatusOK, newAuthor) +} diff --git a/routes/routes.go b/routes/routes.go index 9bf5965..df06f86 100644 --- a/routes/routes.go +++ b/routes/routes.go @@ -57,6 +57,7 @@ func RegisterRoutes(e *echo.Echo) { // Manage Authors a.PUT("/authors", apiv1.AuthorAdd) a.DELETE("/authors/:id", apiv1.AuthorDelete) + a.POST("/authors/:id", apiv1.AuthorUpdate) // Manage Publishers a.PUT("/publishers", apiv1.PublisherAdd)