From a97b14ff3305ea8167a3a1a9d355b4ff3bbef833 Mon Sep 17 00:00:00 2001 From: Christine Dodrill Date: Tue, 14 Jan 2020 23:39:22 +0000 Subject: [PATCH] switchcounter: fix pagination, get individual switches --- frontend/src/Session.elm | 6 ------ switchcounter/storage.go | 1 + switchcounter/switch.go | 33 ++++++++++++++++++++++++++++++++- 3 files changed, 33 insertions(+), 7 deletions(-) delete mode 100644 frontend/src/Session.elm diff --git a/frontend/src/Session.elm b/frontend/src/Session.elm deleted file mode 100644 index d178cfa..0000000 --- a/frontend/src/Session.elm +++ /dev/null @@ -1,6 +0,0 @@ -module Session exposing (Session) - - -type Session - = Guest - | LoggedIn String diff --git a/switchcounter/storage.go b/switchcounter/storage.go index c6bb07b..1a108ed 100644 --- a/switchcounter/storage.go +++ b/switchcounter/storage.go @@ -15,6 +15,7 @@ func New(session *r.Session, mux *http.ServeMux) *Switches { session: session, } + mux.HandleFunc("/switches/id/", result.GetID) mux.HandleFunc("/switches/", result.GetSwitches) mux.HandleFunc("/switches/current", result.Current) mux.HandleFunc("/switches/switch", result.RegisterSwitch) diff --git a/switchcounter/switch.go b/switchcounter/switch.go index 035a83a..cde313e 100644 --- a/switchcounter/switch.go +++ b/switchcounter/switch.go @@ -5,6 +5,7 @@ import ( "encoding/json" "io/ioutil" "net/http" + "path" "strconv" "time" @@ -13,12 +14,29 @@ import ( "within.website/ln" ) +func (s *Switches) ByID(ctx context.Context, id string) (*Switch, error) { + var result Switch + res, err := r.Table("switches"). + Get(id). + Run(s.session) + if err != nil { + return nil, err + } + + err = res.One(&result) + if err != nil { + return nil, err + } + + return &result, nil +} + func (s *Switches) Get(ctx context.Context, limit, page int) ([]Switch, error) { var result []Switch res, err := r.Table("switches"). OrderBy(r.Desc("started_at")). - Limit(limit). Skip(page * limit). + Limit(limit). Run(s.session) if err != nil { return nil, err @@ -84,6 +102,18 @@ func (s *Switches) Switch(ctx context.Context, who string) (Switch, Switch, erro return lastSw, currentSw, nil } +func (s *Switches) GetID(rw http.ResponseWriter, req *http.Request) { + id := path.Base(req.URL.Path) + sw, err := s.ByID(req.Context(), id) + if err != nil { + ln.Error(req.Context(), err) + http.Error(rw, "can't get data", http.StatusInternalServerError) + return + } + + json.NewEncoder(rw).Encode(sw) +} + func (s *Switches) Current(rw http.ResponseWriter, req *http.Request) { var result Switch res, err := r.Table("switches"). @@ -93,6 +123,7 @@ func (s *Switches) Current(rw http.ResponseWriter, req *http.Request) { if err != nil { ln.Error(req.Context(), err) http.Error(rw, "can't get data", http.StatusInternalServerError) + return } err = res.One(&result)