graphicek/server/routes/dashboards.go

105 lines
1.8 KiB
Go
Raw Normal View History

2022-08-23 23:35:36 +02:00
package routes
import (
"basic-sensor-receiver/app"
"net/http"
2022-09-03 21:35:36 +02:00
"strconv"
2022-08-23 23:35:36 +02:00
"github.com/gin-gonic/gin"
)
type postDashboardBody struct {
2022-09-03 21:35:36 +02:00
Id int64 `json:"id"`
Name string `json:"name"`
2022-08-23 23:35:36 +02:00
Contents string `json:"contents"`
}
type putDashboardBody struct {
2022-09-03 21:35:36 +02:00
Name string `json:"name"`
2022-08-23 23:35:36 +02:00
Contents string `json:"contents"`
}
func GetDashboards(s *app.Server) gin.HandlerFunc {
return func(c *gin.Context) {
items, err := s.Services.Dashboards.GetList()
if err != nil {
c.AbortWithError(500, err)
return
}
c.JSON(http.StatusOK, items)
}
}
func GetDashboardById(s *app.Server) gin.HandlerFunc {
return func(c *gin.Context) {
2022-09-03 21:35:36 +02:00
id, err := getIntParam(c, "id")
if err != nil {
c.AbortWithError(400, err)
return
}
2022-08-23 23:35:36 +02:00
item, err := s.Services.Dashboards.GetById(id)
if err != nil {
c.AbortWithError(500, err)
return
}
c.JSON(http.StatusOK, item)
}
}
func PostDashboard(s *app.Server) gin.HandlerFunc {
return func(c *gin.Context) {
body := postDashboardBody{}
if err := c.BindJSON(&body); err != nil {
c.AbortWithError(400, err)
return
}
2022-09-03 21:35:36 +02:00
item, err := s.Services.Dashboards.Create(body.Id, body.Name, body.Contents)
2022-08-23 23:35:36 +02:00
if err != nil {
c.AbortWithError(500, err)
return
}
c.JSON(http.StatusOK, item)
}
}
func PutDashboard(s *app.Server) gin.HandlerFunc {
return func(c *gin.Context) {
2022-09-03 21:35:36 +02:00
id, err := getIntParam(c, "id")
if err != nil {
c.AbortWithError(400, err)
return
}
2022-08-23 23:35:36 +02:00
body := putDashboardBody{}
if err := c.BindJSON(&body); err != nil {
c.AbortWithError(400, err)
return
}
2022-09-03 21:35:36 +02:00
item, err := s.Services.Dashboards.Update(id, body.Name, body.Contents)
2022-08-23 23:35:36 +02:00
if err != nil {
c.AbortWithError(500, err)
return
}
c.JSON(http.StatusOK, item)
}
}
2022-09-03 21:35:36 +02:00
func getIntParam(c *gin.Context, key string) (int64, error) {
value := c.Param(key)
return strconv.ParseInt(value, 10, 64)
}