New books can now be inserted via json payload
All checks were successful
the build was successful

This commit is contained in:
konrad 2017-11-15 15:25:47 +01:00 committed by kolaente
parent cb3a37b483
commit c82068b991
Signed by: konrad
GPG Key ID: F40E70337AB24C9B

View File

@ -1,32 +1,25 @@
package v1 package v1
import ( import (
"encoding/json"
"git.mowie.cc/konrad/Library/models" "git.mowie.cc/konrad/Library/models"
"github.com/labstack/echo" "github.com/labstack/echo"
"net/http" "net/http"
"strings"
) )
type bookPayload struct {
Book models.Book `json:"book" form:"book"`
}
// BookAdd is the handler to add a book // BookAdd is the handler to add a book
func BookAdd(c echo.Context) error { func BookAdd(c echo.Context) error {
// Check for Request Content // Check for Request Content
book := c.FormValue("book") b := new(bookPayload)
if book == "" { if err := c.Bind(b); err != nil {
return c.JSON(http.StatusBadRequest, models.Message{"No book model provided"}) return c.JSON(http.StatusBadRequest, models.Message{"No book model provided"})
} }
// Decode the JSON
var bookstruct models.Book
dec := json.NewDecoder(strings.NewReader(book))
err := dec.Decode(&bookstruct)
if err != nil {
return c.JSON(http.StatusInternalServerError, models.Message{"Error decoding book: " + err.Error()})
}
// Insert the book // Insert the book
newBook, err := models.AddBook(bookstruct) newBook, err := models.AddBook(b.Book)
if err != nil { if err != nil {
return c.JSON(http.StatusInternalServerError, models.Message{"Error"}) return c.JSON(http.StatusInternalServerError, models.Message{"Error"})