2017-11-21 10:38:52 +00:00
|
|
|
package v1
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2017-11-21 10:40:07 +00:00
|
|
|
"fmt"
|
2017-11-21 10:38:52 +00:00
|
|
|
"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
|
2017-11-24 11:39:52 +00:00
|
|
|
if authorToInsert.Lastname == "" && authorToInsert.Forename == "" {
|
|
|
|
return c.JSON(http.StatusBadRequest, models.Message{"Please provide at least one name."})
|
2017-11-21 10:38:52 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// 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)
|
|
|
|
}
|