Library/routes/api/v1/publishers_add_update.go

48 lines
1.2 KiB
Go
Raw Normal View History

package v1
import (
"encoding/json"
2017-11-21 11:10:16 +00:00
"fmt"
"git.mowie.cc/konrad/Library/models"
"github.com/labstack/echo"
"net/http"
"strings"
)
type publisherPayload struct {
Publisher models.Publisher `json:"publisher" form:"publisher"`
}
// PublisherAddOrUpdate is the handler to add a publisher
func PublisherAddOrUpdate(c echo.Context) error {
// Check for Request Content
publisherFromString := c.FormValue("publisher")
var publisherToInsert models.Publisher
if publisherFromString == "" {
b := new(publisherPayload)
if err := c.Bind(b); err != nil {
fmt.Println(err)
return c.JSON(http.StatusBadRequest, models.Message{"No publisher model provided"})
}
publisherToInsert = b.Publisher
} else {
// Decode the JSON
dec := json.NewDecoder(strings.NewReader(publisherFromString))
err := dec.Decode(&publisherToInsert)
if err != nil {
return c.JSON(http.StatusInternalServerError, models.Message{"Error decoding publisher: " + err.Error()})
}
}
// Insert the publisher
newPublisher, err := models.AddOrUpdatePublisher(publisherToInsert)
if err != nil {
return c.JSON(http.StatusInternalServerError, models.Message{"Error"})
}
return c.JSON(http.StatusOK, newPublisher)
}