-
Notifications
You must be signed in to change notification settings - Fork 260
/
query.go
91 lines (86 loc) · 2.39 KB
/
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
// Query handlers.
package httpapi
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"github.com/HouzuoGuo/tiedot/db"
)
// Execute a query and return documents from the result.
func Query(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
var col, q string
if !Require(w, r, "col", &col) {
return
}
if !Require(w, r, "q", &q) {
return
}
var qJson interface{}
if err := json.Unmarshal([]byte(q), &qJson); err != nil {
http.Error(w, fmt.Sprintf("'%v' is not valid JSON.", q), 400)
return
}
dbcol := HttpDB.Use(col)
if dbcol == nil {
http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
return
}
// Evaluate the query
queryResult := make(map[int]struct{})
if err := db.EvalQuery(qJson, dbcol, &queryResult); err != nil {
http.Error(w, fmt.Sprint(err), 400)
return
}
// Construct array of result
resultDocs := make(map[string]interface{}, len(queryResult))
counter := 0
for docID := range queryResult {
doc, _ := dbcol.Read(docID)
if doc != nil {
resultDocs[strconv.Itoa(docID)] = doc
counter++
}
}
// Serialize the array
resp, err := json.Marshal(resultDocs)
if err != nil {
http.Error(w, fmt.Sprintf("Server error: query returned invalid structure"), 500)
return
}
w.Write([]byte(string(resp)))
}
// Execute a query and return number of documents from the result.
func Count(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "must-revalidate")
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
var col, q string
if !Require(w, r, "col", &col) {
return
}
if !Require(w, r, "q", &q) {
return
}
var qJson interface{}
if err := json.Unmarshal([]byte(q), &qJson); err != nil {
http.Error(w, fmt.Sprintf("'%v' is not valid JSON.", q), 400)
return
}
dbcol := HttpDB.Use(col)
if dbcol == nil {
http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
return
}
queryResult := make(map[int]struct{})
if err := db.EvalQuery(qJson, dbcol, &queryResult); err != nil {
http.Error(w, fmt.Sprint(err), 400)
return
}
w.Write([]byte(strconv.Itoa(len(queryResult))))
}