switchcounter: fix pagination, get individual switches

This commit is contained in:
Cadey Ratio 2020-01-14 23:39:22 +00:00
parent bf2e5e9f85
commit a97b14ff33
3 changed files with 33 additions and 7 deletions

View File

@ -1,6 +0,0 @@
module Session exposing (Session)
type Session
= Guest
| LoggedIn String

View File

@ -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)

View File

@ -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)