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.

98 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 Item(g *gin.RouterGroup, db database.Database) {
  12. l := services.Loader{DB: db}
  13. g.GET("/", handler("items", func(c *gin.Context) (interface{}, error) {
  14. return l.ListItems(c, models.ItemFilter{})
  15. }))
  16. g.GET("/:id", handler("item", func(c *gin.Context) (interface{}, error) {
  17. return l.FindItem(c, c.Param("id"))
  18. }))
  19. g.POST("/", handler("item", func(c *gin.Context) (interface{}, error) {
  20. item := models.Item{}
  21. err := c.BindJSON(&item)
  22. if err != nil {
  23. return nil, slerrors.BadRequest("Invalid JSON")
  24. }
  25. group, err := db.Groups().Find(c.Request.Context(), item.GroupID)
  26. if err != nil {
  27. return nil, err
  28. } else if auth.UserID(c) != group.UserID {
  29. return nil, slerrors.NotFound("Group")
  30. }
  31. item.ID = generate.ItemID()
  32. item.UserID = auth.UserID(c)
  33. item.GroupID = group.ID
  34. err = db.Items().Insert(c.Request.Context(), item)
  35. if err != nil {
  36. return nil, err
  37. }
  38. return &models.ItemResult{
  39. Item: item,
  40. Group: group,
  41. }, nil
  42. }))
  43. g.PUT("/:id", handler("item", func(c *gin.Context) (interface{}, error) {
  44. update := models.ItemUpdate{}
  45. err := c.BindJSON(&update)
  46. if err != nil {
  47. return nil, slerrors.BadRequest("Invalid JSON")
  48. }
  49. item, err := l.FindItem(c.Request.Context(), c.Param("id"))
  50. if err != nil {
  51. return nil, err
  52. }
  53. item.Update(update)
  54. err = db.Items().Update(c.Request.Context(), item.Item)
  55. if err != nil {
  56. return nil, err
  57. }
  58. return item, nil
  59. }))
  60. g.DELETE("/:id", handler("item", func(c *gin.Context) (interface{}, error) {
  61. item, err := l.FindItem(c.Request.Context(), c.Param("id"))
  62. if err != nil {
  63. return nil, err
  64. }
  65. tasks, err := db.Tasks().List(c.Request.Context(), models.TaskFilter{
  66. UserID: auth.UserID(c),
  67. ItemIDs: []string{item.ID},
  68. })
  69. if err != nil {
  70. return nil, err
  71. }
  72. if len(tasks) > 0 {
  73. return nil, slerrors.Forbidden("cannot delete item referenced in tasks.")
  74. }
  75. err = db.Items().Delete(c.Request.Context(), item.Item)
  76. if err != nil {
  77. return nil, err
  78. }
  79. return item, nil
  80. }))
  81. }