59 lines
1.5 KiB
Go
59 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 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 datPublisher models.Publisher
|
|
|
|
if publisherFromString == "" {
|
|
b := new(publisherPayload)
|
|
if err := c.Bind(b); err != nil {
|
|
return c.JSON(http.StatusBadRequest, models.Message{"No publisher model provided"})
|
|
}
|
|
datPublisher = b.Publisher
|
|
} else {
|
|
// Decode the JSON
|
|
dec := json.NewDecoder(strings.NewReader(publisherFromString))
|
|
err := dec.Decode(&datPublisher)
|
|
|
|
if err != nil {
|
|
return c.JSON(http.StatusInternalServerError, models.Message{"Error decoding publisher: " + err.Error()})
|
|
}
|
|
}
|
|
|
|
// Check if we have an ID other than the one in the struct
|
|
id := c.Param("id")
|
|
if id != "" {
|
|
// Make int
|
|
publisherID, err := strconv.ParseInt(id, 10, 64)
|
|
|
|
if err != nil {
|
|
return c.JSON(http.StatusInternalServerError, models.Message{"Could not get item id"})
|
|
}
|
|
datPublisher.ID = publisherID
|
|
}
|
|
|
|
// Insert or update the publisher
|
|
newPublisher, err := models.AddOrUpdatePublisher(datPublisher)
|
|
|
|
if err != nil {
|
|
return c.JSON(http.StatusInternalServerError, models.Message{"Error"})
|
|
}
|
|
|
|
return c.JSON(http.StatusOK, newPublisher)
|
|
}
|