-
Notifications
You must be signed in to change notification settings - Fork 140
/
Copy pathjsonapi.go
328 lines (290 loc) · 8.87 KB
/
jsonapi.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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
// Package jsonapi is for using the JSON-API format: parsing, serialization,
// checking the content-type, etc.
package jsonapi
import (
"compress/gzip"
"encoding/json"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/cozy/cozy-stack/pkg/couchdb"
"github.com/labstack/echo/v4"
)
// ContentType is the official mime-type for JSON-API
const ContentType = "application/vnd.api+json"
// Document is JSON-API document, identified by the mediatype
// application/vnd.api+json
// See http://jsonapi.org/format/#document-structure
type Document struct {
Data *json.RawMessage `json:"data,omitempty"`
Errors ErrorList `json:"errors,omitempty"`
Links *LinksList `json:"links,omitempty"`
Meta *Meta `json:"meta,omitempty"`
Included []interface{} `json:"included,omitempty"`
}
// WriteData can be called to write an answer with a JSON-API document
// containing a single object as data into an io.Writer.
func WriteData(w io.Writer, o Object, links *LinksList) error {
var included []interface{}
if inc := o.Included(); inc != nil {
included = make([]interface{}, len(inc))
for i, o := range inc {
data, err := MarshalObject(o)
if err != nil {
return err
}
included[i] = &data
}
}
data, err := MarshalObject(o)
if err != nil {
return err
}
doc := Document{
Data: &data,
Links: links,
Included: included,
}
return json.NewEncoder(w).Encode(doc)
}
// Data can be called to send an answer with a JSON-API document containing a
// single object as data
func Data(c echo.Context, statusCode int, o Object, links *LinksList) error {
resp := c.Response()
w := compressedWriter(c.Request(), resp)
defer func() {
_ = w.Close()
}()
resp.WriteHeader(statusCode)
return WriteData(w, o, links)
}
// DataList can be called to send an multiple-value answer with a
// JSON-API document contains multiple objects.
func DataList(c echo.Context, statusCode int, objs []Object, links *LinksList) error {
count := len(objs)
meta := Meta{Count: &count}
return DataListWithMeta(c, statusCode, meta, objs, links)
}
// DataListWithMeta can be called to send a list of Objects with meta like a
// count, useful to indicate total number of results with pagination.
func DataListWithMeta(c echo.Context, statusCode int, meta Meta, objs []Object, links *LinksList) error {
objsMarshaled := make([]json.RawMessage, len(objs))
for i, o := range objs {
j, err := MarshalObject(o)
if err != nil {
return InternalServerError(err)
}
objsMarshaled[i] = j
}
data, err := json.Marshal(objsMarshaled)
if err != nil {
return InternalServerError(err)
}
doc := Document{
Data: (*json.RawMessage)(&data),
Meta: &meta,
Links: links,
}
resp := c.Response()
w := compressedWriter(c.Request(), resp)
defer func() {
_ = w.Close()
}()
resp.WriteHeader(statusCode)
return json.NewEncoder(w).Encode(doc)
}
func compressedWriter(req *http.Request, resp *echo.Response) io.WriteCloser {
headers := resp.Header()
headers.Set(echo.HeaderContentType, ContentType)
headers.Add(echo.HeaderVary, echo.HeaderAcceptEncoding)
if !acceptGzipEncoding(req) {
return &nopCloser{resp}
}
headers.Set(echo.HeaderContentEncoding, "gzip")
return gzip.NewWriter(resp)
}
// nopCloser adds a Close method to a io.Writer (io.NopCloser does that for
// io.Reader).
type nopCloser struct {
io.Writer
}
func (nopCloser) Close() error { return nil }
func acceptGzipEncoding(req *http.Request) bool {
return strings.Contains(req.Header.Get(echo.HeaderAcceptEncoding), "gzip")
}
// DataRelations can be called to send a Relations page,
// a list of ResourceIdentifier
func DataRelations(c echo.Context, statusCode int, refs []couchdb.DocReference, meta *Meta, links *LinksList, included []Object) error {
data, err := json.Marshal(refs)
if err != nil {
return InternalServerError(err)
}
doc := Document{
Data: (*json.RawMessage)(&data),
Meta: meta,
Links: links,
}
if included != nil {
includedMarshaled := make([]interface{}, len(included))
for i, o := range included {
j, err := MarshalObject(o)
if err != nil {
return InternalServerError(err)
}
includedMarshaled[i] = &j
}
doc.Included = includedMarshaled
}
resp := c.Response()
resp.Header().Set(echo.HeaderContentType, ContentType)
resp.WriteHeader(statusCode)
return json.NewEncoder(resp).Encode(doc)
}
// DataError can be called to send an error answer with a JSON-API document
// containing a single value error.
func DataError(c echo.Context, err *Error) error {
doc := Document{
Errors: ErrorList{err},
}
resp := c.Response()
resp.Header().Set(echo.HeaderContentType, ContentType)
resp.WriteHeader(err.Status)
return json.NewEncoder(resp).Encode(doc)
}
// DataErrorList can be called to send an error answer with a JSON-API document
// containing multiple errors.
func DataErrorList(c echo.Context, errs ...*Error) error {
doc := Document{
Errors: errs,
}
if len(errs) == 0 {
panic("jsonapi.DataErrorList called with empty list.")
}
resp := c.Response()
resp.Header().Set(echo.HeaderContentType, ContentType)
resp.WriteHeader(errs[0].Status)
return json.NewEncoder(resp).Encode(doc)
}
// Bind is used to unmarshal an input JSONApi document. It binds an
// incoming request to a attribute type.
func Bind(body io.Reader, attrs interface{}) (*ObjectMarshalling, error) {
decoder := json.NewDecoder(body)
var doc *Document
if err := decoder.Decode(&doc); err != nil {
return nil, err
}
if doc == nil || doc.Data == nil {
return nil, BadJSON()
}
var obj *ObjectMarshalling
if err := json.Unmarshal(*doc.Data, &obj); err != nil {
return nil, err
}
if obj != nil && obj.Attributes != nil && attrs != nil {
if err := json.Unmarshal(*obj.Attributes, &attrs); err != nil {
return nil, err
}
}
return obj, nil
}
// BindCompound is used to unmarshal an compound input JSONApi document.
func BindCompound(body io.Reader) ([]*ObjectMarshalling, error) {
decoder := json.NewDecoder(body)
var doc *Document
if err := decoder.Decode(&doc); err != nil {
return nil, err
}
if doc.Data == nil {
return nil, BadJSON()
}
var objs []*ObjectMarshalling
if err := json.Unmarshal(*doc.Data, &objs); err != nil {
return nil, err
}
return objs, nil
}
// BindRelations extracts a Relationships request ( a list of ResourceIdentifier)
func BindRelations(req *http.Request) ([]couchdb.DocReference, error) {
var out []couchdb.DocReference
decoder := json.NewDecoder(req.Body)
var doc *Document
if err := decoder.Decode(&doc); err != nil {
return nil, err
}
if doc.Data == nil {
return nil, BadJSON()
}
// Attempt Unmarshaling either as ResourceIdentifier or []ResourceIdentifier
if err := json.Unmarshal(*doc.Data, &out); err != nil {
var ri couchdb.DocReference
if err = json.Unmarshal(*doc.Data, &ri); err != nil {
return nil, err
}
out = []couchdb.DocReference{ri}
return out, nil
}
return out, nil
}
// PaginationCursorToParams transforms a Cursor into url.Values
// the url.Values contains only keys page[limit] & page[cursor]
// if the cursor is Done, the values will be empty.
func PaginationCursorToParams(cursor couchdb.Cursor) (url.Values, error) {
v := url.Values{}
if !cursor.HasMore() {
return v, nil
}
switch c := cursor.(type) {
case *couchdb.StartKeyCursor:
cursorObj := []interface{}{c.NextKey, c.NextDocID}
cursorBytes, err := json.Marshal(cursorObj)
if err != nil {
return nil, err
}
v.Set("page[limit]", strconv.Itoa(c.Limit))
v.Set("page[cursor]", string(cursorBytes))
case *couchdb.SkipCursor:
v.Set("page[limit]", strconv.Itoa(c.Limit))
v.Set("page[skip]", strconv.Itoa(c.Skip))
}
return v, nil
}
// ExtractPaginationCursor creates a Cursor from context Query.
func ExtractPaginationCursor(c echo.Context, defaultLimit, maxLimit int) (couchdb.Cursor, error) {
limit := defaultLimit
if limitString := c.QueryParam("page[limit]"); limitString != "" {
reqLimit, err := strconv.ParseInt(limitString, 10, 32)
if err != nil {
return nil, NewError(http.StatusBadRequest, "page limit is not a number")
}
limit = int(reqLimit)
}
if maxLimit > 0 && limit > maxLimit {
limit = maxLimit
}
if cursor := c.QueryParam("page[cursor]"); cursor != "" {
var parts []interface{}
err := json.Unmarshal([]byte(cursor), &parts)
if err != nil {
return nil, Errorf(http.StatusBadRequest, "bad json cursor %s", cursor)
}
if len(parts) != 2 {
return nil, Errorf(http.StatusBadRequest, "bad cursor length %s", cursor)
}
nextKey := parts[0]
nextDocID, ok := parts[1].(string)
if !ok {
return nil, Errorf(http.StatusBadRequest, "bad cursor id %s", cursor)
}
return couchdb.NewKeyCursor(limit, nextKey, nextDocID), nil
}
if skipString := c.QueryParam("page[skip]"); skipString != "" {
reqSkip, err := strconv.Atoi(skipString)
if err != nil {
return nil, NewError(http.StatusBadRequest, "page skip is not a number")
}
return couchdb.NewSkipCursor(limit, reqSkip), nil
}
return couchdb.NewKeyCursor(limit, nil, ""), nil
}