64 lines
1.5 KiB
Go
64 lines
1.5 KiB
Go
package v1
|
|
|
|
import (
|
|
"encoding/json"
|
|
"git.mowie.cc/konrad/Library/models"
|
|
"github.com/labstack/echo"
|
|
"net/http"
|
|
"strconv"
|
|
"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 datBook models.Book
|
|
|
|
if bookFromString == "" {
|
|
b := new(bookPayload)
|
|
if err := c.Bind(b); err != nil {
|
|
return c.JSON(http.StatusBadRequest, models.Message{"No book model provided"})
|
|
}
|
|
datBook = b.Book
|
|
} else {
|
|
// Decode the JSON
|
|
dec := json.NewDecoder(strings.NewReader(bookFromString))
|
|
err := dec.Decode(&datBook)
|
|
|
|
if err != nil {
|
|
return c.JSON(http.StatusInternalServerError, models.Message{"Error decoding book: " + err.Error()})
|
|
}
|
|
}
|
|
|
|
// Check if we have an ID other than the one in the struct
|
|
id := c.Param("id")
|
|
if id != "" {
|
|
// Make int
|
|
bookID, err := strconv.ParseInt(id, 10, 64)
|
|
|
|
if err != nil {
|
|
return c.JSON(http.StatusInternalServerError, models.Message{"Could not get book id"})
|
|
}
|
|
datBook.ID = bookID
|
|
}
|
|
|
|
// Check if we have at least a title
|
|
if datBook.Title == "" && datBook.ID == 0 {
|
|
return c.JSON(http.StatusBadRequest, models.Message{"You need at least a title to insert a new book!"})
|
|
}
|
|
|
|
// Insert or update the book
|
|
newBook, err := models.AddOrUpdateBook(datBook)
|
|
|
|
if err != nil {
|
|
return c.JSON(http.StatusInternalServerError, models.Message{"Error"})
|
|
}
|
|
|
|
return c.JSON(http.StatusOK, newBook)
|
|
}
|