graphicek/server/routes/dashboards.go

116 lines
2.0 KiB
Go
Raw Normal View History

2022-08-23 23:35:36 +02:00
package routes
import (
"basic-sensor-receiver/app"
"database/sql"
2022-08-23 23:35:36 +02:00
"net/http"
"github.com/gin-gonic/gin"
)
type postDashboardBody struct {
Name string `json:"name" binding:"required"`
Contents string `json:"contents" binding:"required"`
2022-08-23 23:35:36 +02:00
}
type putDashboardBody struct {
Name string `json:"name" binding:"required"`
Contents string `json:"contents" binding:"required"`
2022-08-23 23:35:36 +02:00
}
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) {
id, err := getIntParamOrAbort(c, "id")
if err != nil {
return
}
2022-08-23 23:35:36 +02:00
item, err := s.Services.Dashboards.GetById(id)
if err == sql.ErrNoRows {
c.Status(404)
return
}
2022-08-23 23:35:36 +02:00
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 := bindJSONBodyOrAbort(c, &body); err != nil {
return
}
2022-08-23 23:35:36 +02:00
item, err := s.Services.Dashboards.Create(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) {
id, err := getIntParamOrAbort(c, "id")
if err != nil {
return
}
2022-09-03 21:35:36 +02:00
2022-08-23 23:35:36 +02:00
body := putDashboardBody{}
if err := bindJSONBodyOrAbort(c, &body); err != nil {
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 DeleteDashboard(s *app.Server) gin.HandlerFunc {
return func(c *gin.Context) {
id, err := getIntParamOrAbort(c, "id")
if err != nil {
return
}
err = s.Services.Dashboards.Delete(id)
if err != nil {
c.AbortWithError(500, err)
return
}
c.Status(http.StatusOK)
}
}