2017-10-09 19:06:40 +00:00
|
|
|
package v1
|
|
|
|
|
|
|
|
import (
|
2017-11-16 18:07:32 +00:00
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
2017-11-07 15:35:10 +00:00
|
|
|
"git.mowie.cc/konrad/Library/models"
|
2017-10-09 19:06:40 +00:00
|
|
|
"github.com/labstack/echo"
|
|
|
|
"net/http"
|
2017-11-16 18:07:32 +00:00
|
|
|
"strings"
|
2017-10-09 19:06:40 +00:00
|
|
|
)
|
|
|
|
|
2017-11-15 14:25:47 +00:00
|
|
|
type bookPayload struct {
|
|
|
|
Book models.Book `json:"book" form:"book"`
|
|
|
|
}
|
|
|
|
|
2017-11-21 10:38:52 +00:00
|
|
|
// BookAddOrUpdate is the handler to add a book
|
|
|
|
func BookAddOrUpdate(c echo.Context) error {
|
2017-10-10 07:47:05 +00:00
|
|
|
// Check for Request Content
|
2017-11-16 18:07:32 +00:00
|
|
|
bookFromString := c.FormValue("book")
|
|
|
|
var bookToInsert models.Book
|
|
|
|
|
|
|
|
if bookFromString == "" {
|
|
|
|
b := new(bookPayload)
|
|
|
|
if err := c.Bind(b); err != nil {
|
|
|
|
fmt.Println(err)
|
|
|
|
return c.JSON(http.StatusBadRequest, models.Message{"No book model provided"})
|
|
|
|
}
|
|
|
|
bookToInsert = b.Book
|
|
|
|
} else {
|
|
|
|
// Decode the JSON
|
|
|
|
dec := json.NewDecoder(strings.NewReader(bookFromString))
|
|
|
|
err := dec.Decode(&bookToInsert)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return c.JSON(http.StatusInternalServerError, models.Message{"Error decoding book: " + err.Error()})
|
|
|
|
}
|
2017-10-09 19:06:40 +00:00
|
|
|
}
|
|
|
|
|
2017-11-21 09:33:37 +00:00
|
|
|
// Check if we have at least a title
|
|
|
|
if bookToInsert.Title == "" {
|
|
|
|
return c.JSON(http.StatusBadRequest, models.Message{"You need at least a title to insert a new book!"})
|
|
|
|
}
|
|
|
|
|
2017-10-10 07:47:05 +00:00
|
|
|
// Insert the book
|
2017-11-18 08:32:30 +00:00
|
|
|
newBook, err := models.AddOrUpdateBook(bookToInsert)
|
2017-10-09 19:06:40 +00:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return c.JSON(http.StatusInternalServerError, models.Message{"Error"})
|
|
|
|
}
|
|
|
|
|
2017-10-11 16:17:51 +00:00
|
|
|
return c.JSON(http.StatusOK, newBook)
|
2017-10-09 19:06:40 +00:00
|
|
|
}
|