Library/routes/api/v1/items_add_update.go

59 lines
1.4 KiB
Go

package v1
import (
"encoding/json"
"git.mowie.cc/konrad/Library/models"
"github.com/labstack/echo"
"net/http"
"strconv"
"strings"
)
// ItemAddOrUpdate is the handler to add a item
func ItemAddOrUpdate(c echo.Context) error {
// Check for Request Content
itemFromString := c.FormValue("item")
var datItem *models.Item
if itemFromString == "" {
if err := c.Bind(&datItem); err != nil {
return c.JSON(http.StatusBadRequest, models.Message{"No item model provided"})
}
} else {
// Decode the JSON
dec := json.NewDecoder(strings.NewReader(itemFromString))
err := dec.Decode(&datItem)
if err != nil {
return c.JSON(http.StatusInternalServerError, models.Message{"Error decoding item: " + err.Error()})
}
}
// Check if we have an ID other than the one in the struct
id := c.Param("id")
if id != "" {
// Make int
itemID, err := strconv.ParseInt(id, 10, 64)
if err != nil {
return c.JSON(http.StatusInternalServerError, models.Message{"Could not get item id"})
}
datItem.ID = itemID
}
// Insert or update the item
newItem, err := models.AddOrUpdateItem(*datItem)
if err != nil {
return c.JSON(http.StatusInternalServerError, models.Message{"Error"})
}
// Log the action
err = models.LogAction("Added or updated an item", newItem.ID, c)
if err != nil {
return c.JSON(http.StatusInternalServerError, models.Message{"Could not log"})
}
return c.JSON(http.StatusOK, newItem)
}