graphicek/server/routes/sensors.go

95 lines
1.8 KiB
Go

package routes
import (
"basic-sensor-receiver/app"
"log"
"net/http"
"github.com/gin-gonic/gin"
)
type postOrPutSensorsBody struct {
Name string `json:"name" binding:"required"`
}
func GetSensors(s *app.Server) gin.HandlerFunc {
return func(c *gin.Context) {
sensors, err := s.Services.Sensors.GetList()
if err != nil {
log.Println(err)
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, sensors)
}
}
func PostSensors(s *app.Server) gin.HandlerFunc {
return func(c *gin.Context) {
body := postOrPutSensorsBody{}
bindJSONBodyOrAbort(c, &body)
sensor, err := s.Services.Sensors.Create(body.Name)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
c.JSON(http.StatusOK, sensor)
}
}
func PutSensor(s *app.Server) gin.HandlerFunc {
return func(c *gin.Context) {
sensorId := getIntParamOrAbort(c, "sensor")
body := postOrPutSensorsBody{}
bindJSONBodyOrAbort(c, &body)
sensor, err := s.Services.Sensors.Update(sensorId, body.Name)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
c.JSON(http.StatusOK, sensor)
}
}
func GetSensor(s *app.Server) gin.HandlerFunc {
return func(c *gin.Context) {
sensorId := getIntParamOrAbort(c, "sensor")
body := postOrPutSensorsBody{}
bindJSONBodyOrAbort(c, &body)
sensor, err := s.Services.Sensors.GetById(sensorId)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
c.JSON(http.StatusOK, sensor)
}
}
func DeleteSensor(s *app.Server) gin.HandlerFunc {
return func(c *gin.Context) {
sensorId := getIntParamOrAbort(c, "sensor")
err := s.Services.Sensors.DeleteById(sensorId)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
c.Status(http.StatusOK)
}
}