You've already forked reloading-manager
97 lines
2.0 KiB
Go
97 lines
2.0 KiB
Go
package cartridge
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"git.s.int/reloading-manager/backend/database"
|
|
"git.s.int/reloading-manager/backend/handlers"
|
|
"git.s.int/reloading-manager/backend/models/loads"
|
|
"github.com/labstack/echo/v4"
|
|
"net/http"
|
|
)
|
|
|
|
type response struct {
|
|
Id string `json:"id"`
|
|
Name string `json:"name"`
|
|
}
|
|
|
|
type postRequest struct {
|
|
Name string `json:"name"`
|
|
Meta string `json:"meta"`
|
|
}
|
|
|
|
func Get(c echo.Context) error {
|
|
db := c.(*database.CustomContext).Db
|
|
defer db.Db.Close(context.Background())
|
|
|
|
cartridges, err := db.Loads.GetCartridges(context.Background())
|
|
if err != nil {
|
|
return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
|
|
}
|
|
|
|
var res = make([]response, 0)
|
|
for _, cartridge := range cartridges {
|
|
res = append(res, response{
|
|
Id: cartridge.ID.String(),
|
|
Name: cartridge.Name,
|
|
})
|
|
}
|
|
|
|
return c.JSON(http.StatusOK, handlers.Response[[]response]{
|
|
Payload: res,
|
|
Status: http.StatusText(http.StatusOK),
|
|
})
|
|
}
|
|
|
|
func Post(c echo.Context) error {
|
|
db := c.(*database.CustomContext).Db
|
|
defer db.Db.Close(context.Background())
|
|
|
|
req := postRequest{}
|
|
|
|
err := c.Bind(&req)
|
|
if err != nil {
|
|
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
|
|
}
|
|
|
|
if req.Name == "" {
|
|
return echo.NewHTTPError(http.StatusBadRequest, "name is required")
|
|
}
|
|
|
|
var meta json.RawMessage
|
|
if req.Meta != "" {
|
|
meta = []byte(req.Meta)
|
|
} else {
|
|
meta = []byte("{}")
|
|
}
|
|
|
|
retId, err := db.Loads.CreateCartridge(context.Background(), loads.CreateCartridgeParams{
|
|
Name: req.Name,
|
|
Meta: meta,
|
|
})
|
|
|
|
if err != nil {
|
|
return handlers.BadRequest(c, "already exists")
|
|
}
|
|
|
|
return c.JSON(http.StatusOK, map[string]string{"id": retId.String()})
|
|
}
|
|
|
|
func Delete(c echo.Context) error {
|
|
db := c.(*database.CustomContext).Db
|
|
defer db.Db.Close(context.Background())
|
|
|
|
uid := handlers.ParseUuidOrBadRequest(c, c.Param("id"))
|
|
if uid == nil {
|
|
return nil
|
|
}
|
|
|
|
err := db.Loads.DeleteCartridge(context.Background(), *uid)
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return c.NoContent(http.StatusOK)
|
|
}
|