Library/routes/api/v1/authors_add_update.go

79 lines
2.1 KiB
Go
Raw Normal View History

package v1
import (
"encoding/json"
2018-03-05 11:53:12 +00:00
"git.kolaente.de/konrad/Library/models"
"github.com/labstack/echo"
"net/http"
2017-11-28 14:29:51 +00:00
"strconv"
2017-11-28 15:04:14 +00:00
"strings"
)
// AuthorAddOrUpdate is the handler to add or update an author
func AuthorAddOrUpdate(c echo.Context) error {
// Check for Request Content
authorFromString := c.FormValue("author")
2017-12-07 15:17:18 +00:00
var datAuthor *models.Author
if authorFromString == "" {
2017-12-07 15:17:18 +00:00
if err := c.Bind(&datAuthor); err != nil {
return c.JSON(http.StatusBadRequest, models.Message{"No author model provided."})
}
} else {
// Decode the JSON
dec := json.NewDecoder(strings.NewReader(authorFromString))
2017-11-28 14:29:51 +00:00
err := dec.Decode(&datAuthor)
if err != nil {
return c.JSON(http.StatusInternalServerError, models.Message{"Error decoding author: " + err.Error()})
}
}
// Check if we have at least a Lastname
2017-11-28 14:29:51 +00:00
if datAuthor.Lastname == "" && datAuthor.Forename == "" {
2017-11-24 11:39:52 +00:00
return c.JSON(http.StatusBadRequest, models.Message{"Please provide at least one name."})
}
2017-11-28 15:04:14 +00:00
2017-11-28 14:29:51 +00:00
// Check if we have an ID other than the one in the struct
id := c.Param("id")
if id != "" {
// Make int
authorID, err := strconv.ParseInt(id, 10, 64)
2017-11-28 14:29:51 +00:00
if err != nil {
return c.JSON(http.StatusBadRequest, models.Message{"Invalid ID."})
2017-11-28 14:29:51 +00:00
}
datAuthor.ID = authorID
}
// Check if the author exists
if datAuthor.ID != 0 {
_, exists, err := models.GetAuthorByID(datAuthor.ID)
if err != nil {
2018-01-15 12:20:58 +00:00
return c.JSON(http.StatusInternalServerError, models.Message{"Could not check if the author exists."})
}
if !exists {
2018-01-15 12:20:58 +00:00
return c.JSON(http.StatusNotFound, models.Message{"The author does not exist."})
}
}
2017-11-28 14:29:51 +00:00
// Insert or update the author
2017-12-07 15:17:18 +00:00
newAuthor, err := models.AddOrUpdateAuthor(*datAuthor)
if err != nil {
if models.IsErrAuthorCannotBeEmpty(err) {
2018-01-25 11:23:51 +00:00
return c.JSON(http.StatusBadRequest, models.Message{"Please provide at least a name and a lastname."})
}
return c.JSON(http.StatusInternalServerError, models.Message{"Error"})
}
2017-12-05 13:46:54 +00:00
// Log the action
err = models.LogAction("Added or updated an author", newAuthor.ID, c)
if err != nil {
2018-01-15 12:20:58 +00:00
return c.JSON(http.StatusInternalServerError, models.Message{"Could not log."})
2017-12-05 13:46:54 +00:00
}
return c.JSON(http.StatusOK, newAuthor)
}