-
Notifications
You must be signed in to change notification settings - Fork 5
/
handler_query.go
112 lines (96 loc) · 2.54 KB
/
handler_query.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package handlers
import (
"context"
"encoding/json"
"net/http"
"time"
"github.com/clems4ever/go-graphkb/internal/history"
"github.com/clems4ever/go-graphkb/internal/knowledge"
)
// PostQuery post endpoint to query the graph
func PostQuery(database knowledge.GraphDB, queryHistorizer history.Historizer) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
type QueryRequestBody struct {
Query string `json:"q"`
}
type ColumnType struct {
Name string `json:"name"`
Type string `json:"type"`
}
type QueryResponseBody struct {
Items [][]interface{} `json:"items"`
Columns []ColumnType `json:"columns"`
ExecutionTimeMs time.Duration `json:"execution_time_ms"`
}
requestBody := QueryRequestBody{}
err := json.NewDecoder(r.Body).Decode(&requestBody)
if err != nil {
ReplyWithInternalError(w, err)
return
}
if requestBody.Query == "" {
w.WriteHeader(http.StatusBadRequest)
_, err = w.Write([]byte("Empty 'query' parameter"))
if err != nil {
ReplyWithInternalError(w, err)
}
return
}
querier := knowledge.NewQuerier(database, queryHistorizer)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
res, err := querier.Query(ctx, requestBody.Query)
if err != nil {
ReplyWithInternalError(w, err)
return
}
defer res.Cursor.Close()
columns := make([]ColumnType, 0)
for _, p := range res.Projections {
var colType string
switch p.ExpressionType {
case knowledge.NodeExprType:
colType = "asset"
case knowledge.EdgeExprType:
colType = "relation"
default:
colType = "property"
}
columns = append(columns, ColumnType{
Name: p.Alias,
Type: colType,
})
}
items := make([][]interface{}, 0)
for res.Cursor.HasMore() {
var d interface{}
err := res.Cursor.Read(context.Background(), &d)
if err != nil {
ReplyWithInternalError(w, err)
return
}
dCols := d.([]interface{})
rowDocs := make([]interface{}, 0)
for _, x := range dCols {
switch v := x.(type) {
case knowledge.AssetWithID:
rowDocs = append(rowDocs, v)
case knowledge.RelationWithID:
rowDocs = append(rowDocs, v)
default:
rowDocs = append(rowDocs, v)
}
}
items = append(items, rowDocs)
}
response := QueryResponseBody{
Items: items,
Columns: columns,
ExecutionTimeMs: res.Statistics.Execution / time.Millisecond,
}
err = json.NewEncoder(w).Encode(response)
if err != nil {
ReplyWithInternalError(w, err)
}
}
}