Library/routes/api/v1/books_add_update.go

53 lines
1.2 KiB
Go
Raw Normal View History

package v1
import (
"encoding/json"
"fmt"
2017-11-07 15:35:10 +00:00
"git.mowie.cc/konrad/Library/models"
"github.com/labstack/echo"
"net/http"
"strings"
)
type bookPayload struct {
Book models.Book `json:"book" form:"book"`
}
// BookAddOrUpdate is the handler to add a book
func BookAddOrUpdate(c echo.Context) error {
// Check for Request Content
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()})
}
}
// 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!"})
}
// Insert the book
2017-11-18 08:32:30 +00:00
newBook, err := models.AddOrUpdateBook(bookToInsert)
if err != nil {
return c.JSON(http.StatusInternalServerError, models.Message{"Error"})
}
return c.JSON(http.StatusOK, newBook)
}