2017-11-21 10:38:52 +00:00
|
|
|
package v1
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"git.mowie.cc/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"
|
2017-11-21 10:38:52 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
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")
|
2017-11-28 14:29:51 +00:00
|
|
|
var datAuthor models.Author
|
2017-11-21 10:38:52 +00:00
|
|
|
|
|
|
|
if authorFromString == "" {
|
|
|
|
b := new(authorPayload)
|
|
|
|
if err := c.Bind(b); err != nil {
|
|
|
|
return c.JSON(http.StatusBadRequest, models.Message{"No author model provided"})
|
|
|
|
}
|
2017-11-28 14:29:51 +00:00
|
|
|
datAuthor = b.Author
|
2017-11-21 10:38:52 +00:00
|
|
|
} else {
|
|
|
|
// Decode the JSON
|
|
|
|
dec := json.NewDecoder(strings.NewReader(authorFromString))
|
2017-11-28 14:29:51 +00:00
|
|
|
err := dec.Decode(&datAuthor)
|
2017-11-21 10:38:52 +00:00
|
|
|
|
|
|
|
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-21 10:38:52 +00:00
|
|
|
}
|
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-21 10:38:52 +00:00
|
|
|
|
2017-11-28 14:29:51 +00:00
|
|
|
if err != nil {
|
|
|
|
return c.JSON(http.StatusInternalServerError, models.Message{"Could not get book id"})
|
|
|
|
}
|
|
|
|
datAuthor.ID = authorID
|
|
|
|
}
|
|
|
|
|
|
|
|
// Insert or update the author
|
|
|
|
newAuthor, err := models.AddOrUpdateAuthor(datAuthor)
|
2017-11-21 10:38:52 +00:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return c.JSON(http.StatusInternalServerError, models.Message{"Error"})
|
|
|
|
}
|
|
|
|
|
|
|
|
return c.JSON(http.StatusOK, newAuthor)
|
|
|
|
}
|