/
api.go
237 lines (198 loc) 路 6.08 KB
/
api.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
// Package api contains files responsible for defining and serving the restful api
package api
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"github.com/jackyzha0/nanoDB/index"
"github.com/jackyzha0/nanoDB/log"
"github.com/julienschmidt/httprouter"
)
// GetIndex returns a JSON of all files in db index
func GetIndex(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
log.Info("retrieving index")
files := index.I.List()
// create temporary struct with index data
data := struct {
Files []string `json:"files"`
}{
Files: files,
}
// create json representation and return
w.Header().Set("Content-Type", "application/json")
jsonData, _ := json.Marshal(data)
fmt.Fprintf(w, "%+v", string(jsonData))
}
// GetKey returns the file with that key if found, otherwise return 404
func GetKey(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
key := ps.ByName("key")
log.Info("get key '%s'", key)
file, ok := index.I.Lookup(key)
// if file fetch is successful
if ok {
w.Header().Set("Content-Type", "application/json")
// unpack bytes into map
jsonMap, err := file.ToMap()
if err != nil {
w.WriteHeader(http.StatusBadRequest)
log.WWarn(w, "err key '%s' cannot be parsed into json: %s", key, err.Error())
return
}
// successful field get
w.Header().Set("Content-Type", "application/json")
maxDepth := getMaxDepthParam(r)
resolvedJsonMap := index.ResolveReferences(jsonMap, maxDepth)
jsonData, _ := json.Marshal(resolvedJsonMap)
fmt.Fprintf(w, "%+v", string(jsonData))
return
}
// otherwise write 404
w.WriteHeader(http.StatusNotFound)
log.WWarn(w, "key '%s' not found", key)
}
// GetKeyField returns key's field, 404 if not found
func GetKeyField(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
key := ps.ByName("key")
field := ps.ByName("field")
log.Info("get field '%s' in key '%s'", field, key)
file, ok := index.I.Lookup(key)
// if file fetch is successful
if ok {
// unpack bytes into map
jsonMap, err := file.ToMap()
if err != nil {
w.WriteHeader(http.StatusBadRequest)
log.WWarn(w, "err key '%s' cannot be parsed into json: %s", key, err.Error())
return
}
// lookup value
val, ok := jsonMap[field]
if !ok {
w.WriteHeader(http.StatusBadRequest)
log.WWarn(w, "err key '%s' does not have field '%s'", key, field)
return
}
// successful field get
w.Header().Set("Content-Type", "application/json")
maxDepth := getMaxDepthParam(r)
resolvedValue := index.ResolveReferences(val, maxDepth)
jsonData, _ := json.Marshal(resolvedValue)
fmt.Fprintf(w, "%+v", string(jsonData))
return
}
// otherwise write 404
w.WriteHeader(http.StatusNotFound)
log.WWarn(w, "key '%s' not found", key)
}
// try to find recursive depth param or else return a default
func getMaxDepthParam(r *http.Request) int {
maxDepth := 3
maxDepthStr := r.URL.Query().Get("depth")
parsedInt, err := strconv.Atoi(maxDepthStr)
if err == nil {
maxDepth = parsedInt
}
return maxDepth
}
// PatchKeyField modifies the field of a key
func PatchKeyField(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
key := ps.ByName("key")
field := ps.ByName("field")
log.Info("patch field '%s' in key '%s'", field, key)
// get bytes from request body
bodyBytes, err := ioutil.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
log.WWarn(w, "err reading body with key '%s': %s", key, err.Error())
return
}
// lookup file by key
file, ok := index.I.Lookup(key)
// if file fetch is successful
if ok {
// unpack bytes into map
jsonMap, err := file.ToMap()
if err != nil {
w.WriteHeader(http.StatusBadRequest)
log.WWarn(w, "err key '%s' cannot be parsed into json: %s", key, err.Error())
return
}
// set field value to parsed json
var parsedJSON map[string]interface{}
err = json.Unmarshal(bodyBytes, &parsedJSON)
if err != nil {
// not JSON, set field to string val instead
jsonMap[field] = string(bodyBytes)
} else {
jsonMap[field] = parsedJSON
}
// remarshal to json
jsonData, _ := json.Marshal(jsonMap)
// write to file
err = file.ReplaceContent(string(jsonData))
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.WWarn(w, "err setting content of key '%s': %s", key, err.Error())
return
}
w.WriteHeader(http.StatusOK)
log.WInfo(w, "patch field '%s' of key '%s' successful", field, key)
return
}
// otherwise write 404
w.WriteHeader(http.StatusNotFound)
log.WWarn(w, "key '%s' not found", key)
}
// UpdateKey creates or updates the file with that key with the request body
func UpdateKey(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
key := ps.ByName("key")
log.Info("put key '%s'", key)
file, ok := index.I.Lookup(key)
// get bytes from request body
bodyBytes, err := ioutil.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
log.WWarn(w, "err reading body when key '%s': %s", key, err.Error())
return
}
// update index
err = index.I.Put(file, bodyBytes)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.WWarn(w, "err updating key '%s': %s", key, err.Error())
return
}
// file is updated
if ok {
log.WInfo(w, "update '%s' successful", key)
return
}
log.WInfo(w, "create '%s' successful", key)
}
// RegenerateIndex rebuilds main index with saved directory
func RegenerateIndex(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
index.I.Regenerate()
log.WInfo(w, "regenerated index")
}
// DeleteKey deletes the file associated with the given key, returns 404 if not found
func DeleteKey(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
key := ps.ByName("key")
log.Info("delete key '%s'", key)
file, ok := index.I.Lookup(key)
// if file found delete it
if ok {
err := index.I.Delete(file)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.WWarn(w, "err unable to delete key '%s': '%s'", key, err.Error())
return
}
log.WInfo(w, "delete '%s' successful", key)
return
}
// else state not found
w.WriteHeader(http.StatusNotFound)
log.WWarn(w, "key '%s' does not exist", key)
}