reveil/api/routines.go

90 lines
2.2 KiB
Go
Raw Normal View History

2022-10-02 21:24:53 +00:00
package api
import (
2022-10-04 16:34:37 +00:00
"fmt"
2022-10-02 21:24:53 +00:00
"net/http"
"github.com/gin-gonic/gin"
"git.nemunai.re/nemunaire/reveil/config"
2022-10-04 16:34:37 +00:00
"git.nemunai.re/nemunaire/reveil/model"
2022-10-02 21:24:53 +00:00
)
func declareRoutinesRoutes(cfg *config.Config, router *gin.RouterGroup) {
router.GET("/routines", func(c *gin.Context) {
2022-10-04 16:34:37 +00:00
routines, err := reveil.LoadRoutines(cfg)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": err.Error()})
return
}
2022-10-02 21:24:53 +00:00
2022-10-04 16:34:37 +00:00
c.JSON(http.StatusOK, routines)
2022-10-02 21:24:53 +00:00
})
router.POST("/routines", func(c *gin.Context) {
2022-10-04 16:34:37 +00:00
c.AbortWithStatusJSON(http.StatusNotImplemented, gin.H{"errmsg": "TODO"})
2022-10-02 21:24:53 +00:00
})
2022-10-04 16:34:37 +00:00
routinesRoutes := router.Group("/routines/:tid")
routinesRoutes.Use(func(c *gin.Context) {
routines, err := reveil.LoadRoutines(cfg)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": err.Error()})
return
}
for _, t := range routines {
if t.Id.ToString() == c.Param("tid") {
c.Set("routine", t)
c.Next()
return
}
}
c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"errmsg": "Routine not found"})
})
2022-10-02 21:24:53 +00:00
routinesRoutes.GET("", func(c *gin.Context) {
c.JSON(http.StatusOK, c.MustGet("routine"))
})
routinesRoutes.PUT("", func(c *gin.Context) {
2022-10-04 16:34:37 +00:00
oldroutine := c.MustGet("routine").(*reveil.Routine)
var routine reveil.Routine
if err := c.ShouldBindJSON(&routine); err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"errmsg": err.Error()})
return
}
if routine.Name != oldroutine.Name {
err := oldroutine.Rename(routine.Name)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": fmt.Sprintf("Unable to rename the routine: %s", err.Error())})
return
}
}
// TODO: change actions
c.JSON(http.StatusOK, oldroutine)
2022-10-02 21:24:53 +00:00
})
routinesRoutes.DELETE("", func(c *gin.Context) {
2022-10-04 16:34:37 +00:00
routine := c.MustGet("routine").(*reveil.Routine)
2022-10-02 21:24:53 +00:00
2022-10-04 16:34:37 +00:00
err := routine.Remove()
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": fmt.Sprintf("Unable to remove the routine: %s", err.Error())})
return
}
2022-10-02 21:24:53 +00:00
2022-10-04 16:34:37 +00:00
c.JSON(http.StatusOK, nil)
})
2022-12-08 18:33:51 +00:00
routinesRoutes.POST("/run", func(c *gin.Context) {
routine := c.MustGet("routine").(*reveil.Routine)
go routine.Launch(cfg)
c.JSON(http.StatusOK, true)
})
2022-10-02 21:24:53 +00:00
}