package api import ( "git.aiterp.net/lucifer/new-server/app/config" "git.aiterp.net/lucifer/new-server/app/services/publisher" "git.aiterp.net/lucifer/new-server/models" "github.com/gin-gonic/gin" "regexp" ) func Scenes(r gin.IRoutes) { nonNumericRegex := regexp.MustCompile("[a-zA-Z ]") findScene := func(c *gin.Context) (*models.Scene, error) { param := c.Param("id") if nonNumericRegex.MatchString(param) { return config.SceneRepository().FindName(ctxOf(c), param) } else { return config.SceneRepository().Find(ctxOf(c), intParam(c, "id")) } } r.GET("", handler(func(c *gin.Context) (interface{}, error) { return config.SceneRepository().FetchAll(ctxOf(c)) })) r.GET("/:id", handler(func(c *gin.Context) (interface{}, error) { return findScene(c) })) r.POST("", handler(func(c *gin.Context) (interface{}, error) { var body models.Scene err := parseBody(c, &body) if err != nil { return nil, err } err = body.Validate() if err != nil { return nil, err } err = config.SceneRepository().Save(ctxOf(c), &body) if err != nil { return nil, err } publisher.Global().UpdateScene(body) return body, nil })) r.PUT("/:id", handler(func(c *gin.Context) (interface{}, error) { var body models.Scene err := parseBody(c, &body) if err != nil { return nil, err } scene, err := findScene(c) if err != nil { return nil, err } body.ID = scene.ID err = body.Validate() if err != nil { return nil, err } err = config.SceneRepository().Save(ctxOf(c), &body) if err != nil { return nil, err } publisher.Global().UpdateScene(body) return body, nil })) }