Changed endpoints and db queries, chart now shows suggested mins and maxes
This commit is contained in:
21
Database.go
21
Database.go
@@ -39,6 +39,27 @@ func writeSnapshotToDb(snapshotSub *SnapshotSubmission) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func getLastSnapshotRecordFromDb() (*SnapshotRecord, error) {
|
||||
var snapshotRecord SnapshotRecord
|
||||
query := "SELECT `%s`, `%s`, `%s`, `%s`, `%s` FROM `snapshots` ORDER BY `id` DESC LIMIT 1;"
|
||||
rows, err := ClimateDb.Query(fmt.Sprintf(query, "id", "temp", "humidity", "co2", "time"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows.Next()
|
||||
err = rows.Scan(
|
||||
&snapshotRecord.Id,
|
||||
&snapshotRecord.Temp,
|
||||
&snapshotRecord.Humidity,
|
||||
&snapshotRecord.Co2,
|
||||
&snapshotRecord.Timestamp,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &snapshotRecord, nil
|
||||
}
|
||||
|
||||
func getSnapshotRecordsFromDb(minuteAgo int) ([]*SnapshotRecord, error) {
|
||||
snapshots := make([]*SnapshotRecord, 0)
|
||||
query := "SELECT `%s`, `%s`, `%s`, `%s`, `%s` FROM `snapshots` WHERE `%s` > date_sub(now(), interval %v minute) ORDER BY `id` DESC;"
|
||||
|
||||
@@ -39,6 +39,7 @@ func startServer() {
|
||||
r.HandleFunc("/since/{mins}", showCharts).Methods("GET")
|
||||
r.HandleFunc("/data/", sendData).Methods("GET")
|
||||
r.HandleFunc("/data/since/{mins}", sendData).Methods("GET")
|
||||
r.HandleFunc("/data/last/", sendLastSnapshot).Methods("GET")
|
||||
r.HandleFunc("/", saveSnapshot).Methods("POST")
|
||||
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("static/"))))
|
||||
http.Handle("/", r)
|
||||
@@ -84,6 +85,25 @@ func sendData(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
func sendLastSnapshot(w http.ResponseWriter, r *http.Request) {
|
||||
record, err := getLastSnapshotRecordFromDb()
|
||||
if err != nil {
|
||||
sendInternalError(fmt.Errorf("couldn't read last snapshot from the database: %w", err), w, r)
|
||||
return
|
||||
}
|
||||
json, err := createJsonFromSnapshotRecords(record)
|
||||
if err != nil {
|
||||
sendInternalError(fmt.Errorf("couldn't create a json from the last record: %w", err), w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, err = fmt.Fprintf(w, string(json))
|
||||
if err != nil {
|
||||
sendInternalError(err, w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func saveSnapshot(w http.ResponseWriter, r *http.Request) {
|
||||
snapshotSub, err := createSnapshotSubFromJsonBodyStream(r.Body)
|
||||
if err != nil {
|
||||
|
||||
Reference in New Issue
Block a user