Files
2020-02-29 16:54:38 +01:00

131 lines
2.8 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package api
import (
"github.com/gin-gonic/gin"
"github.com/gisle/stufflog/database"
"github.com/gisle/stufflog/models"
"github.com/gisle/stufflog/services"
"github.com/gisle/stufflog/slerrors"
"sort"
)
func Items(g *gin.RouterGroup, db database.Database, auth *services.AuthService) {
type resObj struct {
Item *models.Item `json:"item,omitempty"`
Items []*models.Item `json:"items,omitempty"`
}
g.Use(auth.GinSessionMiddleware(true))
// GET / – List own items
g.GET("/", func(c *gin.Context) {
user := auth.UserFromContext(c)
items, err := db.Items().ListUser(c.Request.Context(), *user)
if err != nil {
slerrors.GinRespond(c, err)
return
}
if items == nil {
items = []*models.Item{}
}
sort.Sort(models.ItemsByName(items))
c.JSON(200, resObj{Items: items})
})
// GET /:id – Find an item
g.GET("/:id", func(c *gin.Context) {
user := auth.UserFromContext(c)
item, err := db.Items().FindID(c.Request.Context(), c.Param("id"))
if err != nil {
slerrors.GinRespond(c, err)
return
}
if item.UserID != user.ID {
slerrors.GinRespond(c, slerrors.NotFound("Item"))
return
}
c.JSON(200, resObj{Item: item})
})
// POST / – Create an item
g.POST("/", func(c *gin.Context) {
user := auth.UserFromContext(c)
item := models.Item{}
err := c.BindJSON(&item)
if err != nil {
slerrors.GinRespond(c, &slerrors.SLError{Code: 400, Text: err.Error()})
return
}
item.GenerateID()
item.UserID = user.ID
err = db.Items().Insert(c.Request.Context(), item)
if err != nil {
slerrors.GinRespond(c, err)
return
}
c.JSON(200, resObj{Item: &item})
})
// PATCH /:id – Update an item
g.PATCH("/:id", func(c *gin.Context) {
user := auth.UserFromContext(c)
updates := make([]*models.ItemUpdate, 0, 8)
err := c.BindJSON(&updates)
if err != nil {
slerrors.GinRespond(c, &slerrors.SLError{Code: 400, Text: err.Error()})
return
}
item, err := db.Items().FindID(c.Request.Context(), c.Param("id"))
if err != nil {
slerrors.GinRespond(c, err)
return
}
if item.UserID != user.ID {
slerrors.GinRespond(c, slerrors.NotFound("Item"))
return
}
item, err = db.Items().Update(c.Request.Context(), *item, updates)
if err != nil {
slerrors.GinRespond(c, err)
return
}
c.JSON(200, resObj{Item: item})
})
// DELETE /:id – Delete an item
g.DELETE("/:id", func(c *gin.Context) {
user := auth.UserFromContext(c)
item, err := db.Items().FindID(c.Request.Context(), c.Param("id"))
if err != nil {
slerrors.GinRespond(c, err)
return
}
if item.UserID != user.ID {
slerrors.GinRespond(c, slerrors.NotFound("Period"))
return
}
err = db.Items().Remove(c.Request.Context(), *item)
if err != nil {
slerrors.GinRespond(c, err)
return
}
c.JSON(200, resObj{Item: item})
})
}