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

4 years ago
  1. package api
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "github.com/gissleh/stufflog/database"
  5. "github.com/gissleh/stufflog/internal/auth"
  6. "github.com/gissleh/stufflog/internal/generate"
  7. "github.com/gissleh/stufflog/internal/slerrors"
  8. "github.com/gissleh/stufflog/models"
  9. "github.com/gissleh/stufflog/services"
  10. )
  11. func Group(g *gin.RouterGroup, db database.Database) {
  12. l := services.Loader{DB: db}
  13. g.GET("/", handler("groups", func(c *gin.Context) (interface{}, error) {
  14. return l.ListGroups(c, models.GroupFilter{})
  15. }))
  16. g.GET("/:id", handler("group", func(c *gin.Context) (interface{}, error) {
  17. return l.FindGroup(c, c.Param("id"))
  18. }))
  19. g.POST("/", handler("group", func(c *gin.Context) (interface{}, error) {
  20. group := models.Group{}
  21. err := c.BindJSON(&group)
  22. if err != nil {
  23. return nil, slerrors.BadRequest("Invalid JSON")
  24. }
  25. group.ID = generate.GroupID()
  26. group.UserID = auth.UserID(c)
  27. err = db.Groups().Insert(c.Request.Context(), group)
  28. if err != nil {
  29. return nil, err
  30. }
  31. return &models.GroupResult{
  32. Group: group,
  33. Items: []*models.Item{},
  34. }, nil
  35. }))
  36. g.PUT("/:id", handler("group", func(c *gin.Context) (interface{}, error) {
  37. update := models.GroupUpdate{}
  38. err := c.BindJSON(&update)
  39. if err != nil {
  40. return nil, slerrors.BadRequest("Invalid JSON")
  41. }
  42. group, err := db.Groups().Find(c.Request.Context(), c.Param("id"))
  43. if err != nil {
  44. return nil, err
  45. } else if auth.UserID(c) != group.UserID {
  46. return nil, slerrors.NotFound("Item")
  47. }
  48. group.Update(update)
  49. err = db.Groups().Update(c.Request.Context(), *group)
  50. if err != nil {
  51. return nil, err
  52. }
  53. return l.FindGroup(c, group.ID)
  54. }))
  55. g.DELETE("/:id", handler("group", func(c *gin.Context) (interface{}, error) {
  56. group, err := l.FindGroup(c, c.Param("id"))
  57. if err != nil {
  58. return nil, err
  59. }
  60. if len(group.Items) > 0 {
  61. return nil, slerrors.Forbidden("cannot delete non-empty group.")
  62. }
  63. goals, err := db.Goals().List(c.Request.Context(), models.GoalFilter{GroupIDs: []string{group.ID}})
  64. if err != nil {
  65. return nil, err
  66. }
  67. if len(goals) > 0 {
  68. return nil, slerrors.Forbidden("cannot delete group with goals.")
  69. }
  70. err = db.Groups().Delete(c.Request.Context(), group.Group)
  71. if err != nil {
  72. return nil, err
  73. }
  74. return group, nil
  75. }))
  76. }