You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
90 lines
2.3 KiB
90 lines
2.3 KiB
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 Group(g *gin.RouterGroup, db database.Database) {
|
|
l := services.Loader{DB: db}
|
|
|
|
g.GET("/", handler("groups", func(c *gin.Context) (interface{}, error) {
|
|
return l.ListGroups(c, models.GroupFilter{})
|
|
}))
|
|
|
|
g.GET("/:id", handler("group", func(c *gin.Context) (interface{}, error) {
|
|
return l.FindGroup(c, c.Param("id"))
|
|
}))
|
|
|
|
g.POST("/", handler("group", func(c *gin.Context) (interface{}, error) {
|
|
group := models.Group{}
|
|
err := c.BindJSON(&group)
|
|
if err != nil {
|
|
return nil, slerrors.BadRequest("Invalid JSON")
|
|
}
|
|
group.ID = generate.GroupID()
|
|
group.UserID = auth.UserID(c)
|
|
|
|
err = db.Groups().Insert(c.Request.Context(), group)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &models.GroupResult{
|
|
Group: group,
|
|
Items: []*models.Item{},
|
|
}, nil
|
|
}))
|
|
|
|
g.PUT("/:id", handler("group", func(c *gin.Context) (interface{}, error) {
|
|
update := models.GroupUpdate{}
|
|
err := c.BindJSON(&update)
|
|
if err != nil {
|
|
return nil, slerrors.BadRequest("Invalid JSON")
|
|
}
|
|
|
|
group, err := db.Groups().Find(c.Request.Context(), c.Param("id"))
|
|
if err != nil {
|
|
return nil, err
|
|
} else if auth.UserID(c) != group.UserID {
|
|
return nil, slerrors.NotFound("Item")
|
|
}
|
|
|
|
group.Update(update)
|
|
err = db.Groups().Update(c.Request.Context(), *group)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return l.FindGroup(c, group.ID)
|
|
}))
|
|
|
|
g.DELETE("/:id", handler("group", func(c *gin.Context) (interface{}, error) {
|
|
group, err := l.FindGroup(c, c.Param("id"))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(group.Items) > 0 {
|
|
return nil, slerrors.Forbidden("cannot delete non-empty group.")
|
|
}
|
|
goals, err := db.Goals().List(c.Request.Context(), models.GoalFilter{GroupIDs: []string{group.ID}})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(goals) > 0 {
|
|
return nil, slerrors.Forbidden("cannot delete group with goals.")
|
|
}
|
|
|
|
err = db.Groups().Delete(c.Request.Context(), group.Group)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return group, nil
|
|
}))
|
|
}
|