package api import ( "github.com/gin-gonic/gin" "github.com/gissleh/stufflog/database" "github.com/gissleh/stufflog/internal/auth" "github.com/gissleh/stufflog/internal/generate" "github.com/gissleh/stufflog/internal/slerrors" "github.com/gissleh/stufflog/models" "github.com/gissleh/stufflog/services" ) func Item(g *gin.RouterGroup, db database.Database) { l := services.Loader{DB: db} g.GET("/", handler("items", func(c *gin.Context) (interface{}, error) { return l.ListItems(c, models.ItemFilter{}) })) g.GET("/:id", handler("item", func(c *gin.Context) (interface{}, error) { return l.FindItem(c, c.Param("id")) })) g.POST("/", handler("item", func(c *gin.Context) (interface{}, error) { item := models.Item{} err := c.BindJSON(&item) if err != nil { return nil, slerrors.BadRequest("Invalid JSON") } group, err := db.Groups().Find(c.Request.Context(), item.GroupID) if err != nil { return nil, err } else if auth.UserID(c) != group.UserID { return nil, slerrors.NotFound("Group") } item.ID = generate.ItemID() item.UserID = auth.UserID(c) item.GroupID = group.ID err = db.Items().Insert(c.Request.Context(), item) if err != nil { return nil, err } return &models.ItemResult{ Item: item, Group: group, }, nil })) g.PUT("/:id", handler("item", func(c *gin.Context) (interface{}, error) { update := models.ItemUpdate{} err := c.BindJSON(&update) if err != nil { return nil, slerrors.BadRequest("Invalid JSON") } item, err := l.FindItem(c.Request.Context(), c.Param("id")) if err != nil { return nil, err } item.Update(update) err = db.Items().Update(c.Request.Context(), item.Item) if err != nil { return nil, err } return item, nil })) g.DELETE("/:id", handler("item", func(c *gin.Context) (interface{}, error) { item, err := l.FindItem(c.Request.Context(), c.Param("id")) if err != nil { return nil, err } tasks, err := db.Tasks().List(c.Request.Context(), models.TaskFilter{ UserID: auth.UserID(c), ItemIDs: []string{item.ID}, }) if err != nil { return nil, err } if len(tasks) > 0 { return nil, slerrors.Forbidden("cannot delete item referenced in tasks.") } err = db.Items().Delete(c.Request.Context(), item.Item) if err != nil { return nil, err } return item, nil })) }