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.

80 lines
1.6 KiB

  1. package api
  2. import (
  3. "git.aiterp.net/lucifer/new-server/app/config"
  4. "git.aiterp.net/lucifer/new-server/app/services/publisher"
  5. "git.aiterp.net/lucifer/new-server/models"
  6. "github.com/gin-gonic/gin"
  7. "regexp"
  8. )
  9. func Scenes(r gin.IRoutes) {
  10. nonNumericRegex := regexp.MustCompile("[a-zA-Z ]")
  11. findScene := func(c *gin.Context) (*models.Scene, error) {
  12. param := c.Param("id")
  13. if nonNumericRegex.MatchString(param) {
  14. return config.SceneRepository().FindName(ctxOf(c), param)
  15. } else {
  16. return config.SceneRepository().Find(ctxOf(c), intParam(c, "id"))
  17. }
  18. }
  19. r.GET("", handler(func(c *gin.Context) (interface{}, error) {
  20. return config.SceneRepository().FetchAll(ctxOf(c))
  21. }))
  22. r.GET("/:id", handler(func(c *gin.Context) (interface{}, error) {
  23. return findScene(c)
  24. }))
  25. r.POST("", handler(func(c *gin.Context) (interface{}, error) {
  26. var body models.Scene
  27. err := parseBody(c, &body)
  28. if err != nil {
  29. return nil, err
  30. }
  31. err = body.Validate()
  32. if err != nil {
  33. return nil, err
  34. }
  35. err = config.SceneRepository().Save(ctxOf(c), &body)
  36. if err != nil {
  37. return nil, err
  38. }
  39. publisher.Global().UpdateScene(body)
  40. return body, nil
  41. }))
  42. r.PUT("/:id", handler(func(c *gin.Context) (interface{}, error) {
  43. var body models.Scene
  44. err := parseBody(c, &body)
  45. if err != nil {
  46. return nil, err
  47. }
  48. scene, err := findScene(c)
  49. if err != nil {
  50. return nil, err
  51. }
  52. body.ID = scene.ID
  53. err = body.Validate()
  54. if err != nil {
  55. return nil, err
  56. }
  57. err = config.SceneRepository().Save(ctxOf(c), &body)
  58. if err != nil {
  59. return nil, err
  60. }
  61. publisher.Global().UpdateScene(body)
  62. return body, nil
  63. }))
  64. }