forked from gobench-io/gobench
-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.go
84 lines (73 loc) · 1.75 KB
/
graph.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package web
import (
"context"
"net/http"
"strconv"
"github.com/go-chi/chi"
"github.com/go-chi/render"
"github.com/thoverik/gobench/ent"
"github.com/thoverik/gobench/ent/graph"
)
func graphCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
graphID, err := strconv.Atoi(chi.URLParam(r, "graphID"))
if err != nil {
http.Error(w, http.StatusText(404), 404)
return
}
g, err := db.Graph.
Query().
Where(graph.ID(graphID)).
Only(r.Context())
if err != nil {
http.Error(w, http.StatusText(404), 404)
return
}
ctx := context.WithValue(r.Context(), webKey("graph"), g)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func listGraphs(w http.ResponseWriter, r *http.Request) {
graphs, err := db.Graph.
Query().
All(r.Context())
if err != nil {
render.Render(w, r, ErrInternalServer(err))
return
}
if err := render.RenderList(w, r, newGraphListResponse(graphs)); err != nil {
render.Render(w, r, ErrRender(err))
return
}
}
func getGraph(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
g, ok := ctx.Value(webKey("graph")).(*ent.Graph)
if !ok {
http.Error(w, http.StatusText(422), 422)
return
}
if err := render.Render(w, r, newGraphResponse(g)); err != nil {
render.Render(w, r, ErrRender(err))
return
}
}
func getGraphMetrics(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
g, ok := ctx.Value(webKey("graph")).(*ent.Graph)
if !ok {
http.Error(w, http.StatusText(422), 422)
return
}
ms, err := g.
QueryMetrics().
All(ctx)
if err != nil {
render.Render(w, r, ErrInternalServer(err))
return
}
if err := render.RenderList(w, r, newMetricListResponse(ms)); err != nil {
render.Render(w, r, ErrRender(err))
return
}
}