Skip to content

Commit

Permalink
Use map instead of array for all devices apis (#60)
Browse files Browse the repository at this point in the history
  • Loading branch information
andig authored Dec 25, 2019
1 parent 4fd8b31 commit f792d6d
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 8 deletions.
9 changes: 5 additions & 4 deletions server/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,16 +58,17 @@ func (h *Httpd) allDevicesHandler(
) func(http.ResponseWriter, *http.Request) {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ids := h.mc.SortedIDs()
res := make([]apiData, 0)
res := make(map[string]apiData)

for _, id := range ids {
readings, err := readingsProvider(id)
if err != nil {
// Skip this meter, it will simply not be displayed
continue
}

data := apiData{device: id, readings: readings}
res = append(res, data)
data := apiData{readings: readings}
res[id] = data
}

if len(res) == 0 {
Expand Down Expand Up @@ -102,7 +103,7 @@ func (h *Httpd) singleDeviceHandler(
return
}

data := apiData{device: id, readings: readings}
data := apiData{readings: readings}

w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(data); err != nil {
Expand Down
6 changes: 2 additions & 4 deletions server/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,15 @@ import (
"sort"
)

// apiData combines readings with associated device id for JSON encoding
// using kvslice it ensured order export of the readings map
// apiData combines readings with timestamps and uses
// kvslice to ensure ordered export of the readings map
type apiData struct {
device string
readings *Readings
}

// MarshalJSON creates device api json for export
func (d apiData) MarshalJSON() ([]byte, error) {
res := kvslice{
{"Device", d.device},
{"Timestamp", d.readings.Timestamp},
{"Unix", d.readings.Timestamp.Unix()},
}
Expand Down

0 comments on commit f792d6d

Please sign in to comment.