Library/routes/api/v1/publishers_add_update.go

60 lines
1.5 KiB
Go

package v1
import (
"encoding/json"
"git.mowie.cc/konrad/Library/models"
"github.com/labstack/echo"
"net/http"
"strconv"
"strings"
)
// 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(models.Publisher)
if err := c.Bind(&datPublisher); err != nil {
return c.JSON(http.StatusBadRequest, models.Message{"No publisher model provided"})
}
} 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"})
}
// Log the action
err = models.LogAction("Added or updated a publisher", newPublisher.ID, c)
if err != nil {
return c.JSON(http.StatusInternalServerError, models.Message{"Could not log"})
}
return c.JSON(http.StatusOK, newPublisher)
}