graphicek/server/routes/sensors.go

114 lines
2.3 KiB
Go
Raw Permalink Normal View History

2022-08-13 23:39:18 +02:00
package routes
2022-08-13 23:33:50 +02:00
import (
2022-08-13 23:39:18 +02:00
"basic-sensor-receiver/app"
"log"
2022-08-13 23:33:50 +02:00
"net/http"
"github.com/gin-gonic/gin"
)
type postOrPutSensorsBody struct {
Name string `json:"name" binding:"required"`
Type *string `json:"type"`
MqttBrokerId *int `json:"mqttBrokerId"`
MqttTopic *string `json:"mqttTopic"`
MqttPath *string `json:"mqttPath"`
2022-08-28 11:56:03 +02:00
}
2022-08-13 23:39:18 +02:00
func GetSensors(s *app.Server) gin.HandlerFunc {
2022-08-13 23:33:50 +02:00
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()})
2022-08-13 23:33:50 +02:00
return
}
c.JSON(http.StatusOK, sensors)
}
}
2022-08-28 11:56:03 +02:00
func PostSensors(s *app.Server) gin.HandlerFunc {
return func(c *gin.Context) {
body := postOrPutSensorsBody{}
if err := bindJSONBodyOrAbort(c, &body); err != nil {
return
}
2022-08-28 11:56:03 +02:00
sensor, err := s.Services.Sensors.Create(body.Name, body.Type, body.MqttBrokerId, body.MqttTopic, body.MqttPath)
2022-08-28 11:56:03 +02:00
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
c.JSON(http.StatusOK, sensor)
}
}
2022-08-28 21:47:36 +02:00
func PutSensor(s *app.Server) gin.HandlerFunc {
2022-08-28 11:56:03 +02:00
return func(c *gin.Context) {
sensorId, err := getIntParamOrAbort(c, "sensor")
if err != nil {
return
}
2022-08-28 11:56:03 +02:00
body := postOrPutSensorsBody{}
if err := bindJSONBodyOrAbort(c, &body); err != nil {
return
}
2022-08-28 11:56:03 +02:00
sensor, err := s.Services.Sensors.Update(sensorId, body.Name, body.Type, body.MqttBrokerId, body.MqttTopic, body.MqttPath)
2022-08-28 11:56:03 +02:00
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
c.JSON(http.StatusOK, sensor)
}
}
2022-08-28 12:30:37 +02:00
func GetSensor(s *app.Server) gin.HandlerFunc {
return func(c *gin.Context) {
sensorId, err := getIntParamOrAbort(c, "sensor")
if err != nil {
return
}
2022-08-28 12:30:37 +02:00
body := postOrPutSensorsBody{}
if err := bindJSONBodyOrAbort(c, &body); err != nil {
return
}
2022-08-28 12:30:37 +02:00
sensor, err := s.Services.Sensors.GetById(sensorId)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
c.JSON(http.StatusOK, sensor)
}
}
2022-08-28 21:47:36 +02:00
func DeleteSensor(s *app.Server) gin.HandlerFunc {
return func(c *gin.Context) {
sensorId, err := getIntParamOrAbort(c, "sensor")
if err != nil {
return
}
2022-08-28 21:47:36 +02:00
err = s.Services.Sensors.DeleteById(sensorId)
2022-08-28 21:47:36 +02:00
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
c.Status(http.StatusOK)
}
}