diff --git a/db/get-db.http b/db/get-db.http new file mode 100644 index 0000000..f1ef739 --- /dev/null +++ b/db/get-db.http @@ -0,0 +1,7 @@ +@room-id = B3 + +### GET last value of temp, co2, humidity, windows states +GET http://localhost:8080/api/v1/rooms/{{room-id}}/current + +### GET all rooms +GET http://localhost:8080/api/v1/rooms diff --git a/db/src/rest/rest.go b/db/src/rest/rest.go index f0a6535..ea935ed 100644 --- a/db/src/rest/rest.go +++ b/db/src/rest/rest.go @@ -2,6 +2,7 @@ package rest import ( "context" + "fmt" "gateway/influx" "net/http" @@ -27,6 +28,7 @@ func (g *RestGateway) setupRoutes() { v1 := g.engine.Group("/api/v1") { v1.GET("/rooms", g.getRooms) + v1.GET("/rooms/:room-id/current", g.getRoomCurrent) } } @@ -61,3 +63,30 @@ func (g *RestGateway) getRooms(c *gin.Context) { c.JSON(http.StatusOK, rooms) } + +// GET /api/v1/rooms/{room-id}/current +func (g *RestGateway) getRoomCurrent(c *gin.Context) { + roomID := c.Param("room-id") + + // Get the last record for the specific room + query := fmt.Sprintf(`SELECT * FROM "provence" WHERE "room" = '%s' ORDER BY time DESC LIMIT 1`, roomID) + + // Using context.Background() as seen in working snippet + it, err := g.influxGateway.Query(context.Background(), query) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + if it.Next() { + c.JSON(http.StatusOK, it.Value()) + return + } + + if err := it.Err(); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.JSON(http.StatusNotFound, gin.H{"error": "Room not found or no data available"}) +}