forked from rs/rest-layer
/
resource.go
417 lines (384 loc) · 12.1 KB
/
resource.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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
package resource
import (
"context"
"fmt"
"net/url"
"sort"
"time"
"github.com/rs/rest-layer/schema"
)
// Resource holds information about a class of items exposed on the API
type Resource struct {
parentField string
name string
path string
schema schema.Schema
validator validatorFallback
storage storageHandler
conf Conf
resources subResources
aliases map[string]url.Values
hooks eventHandler
}
type subResources []*Resource
// get gets a sub resource by its name
func (sr subResources) get(name string) *Resource {
i := sort.Search(len(sr), func(i int) bool {
return sr[i].name >= name
})
if i >= len(sr) {
return nil
}
r := sr[i]
if r.name != name {
return nil
}
return r
}
// add adds the resource to the subResources in a pre-sorted way
func (sr *subResources) add(rsrc *Resource) {
for i, r := range *sr {
if rsrc.name < r.name {
*sr = append((*sr)[:i], append(subResources{rsrc}, (*sr)[i:]...)...)
return
}
}
*sr = append(*sr, rsrc)
}
// validatorFallback wraps a validator and fallback on given schema if the GetField
// returns nil on a given name
type validatorFallback struct {
schema.Validator
fallback schema.Schema
}
func (v validatorFallback) GetField(name string) *schema.Field {
if f := v.Validator.GetField(name); f != nil {
return f
}
return v.fallback.GetField(name)
}
// connection is a special internal validator to hook a validator of a sub resource
// to the resource validator in order to allow embedding of sub resources during
// field selection. Those connections are set on a fallback schema.
type connection struct {
path string
}
func (v connection) Validate(value interface{}) (interface{}, error) {
// no validation needed
return value, nil
}
// new creates a new resource with provided spec, handler and config
func new(name string, s schema.Schema, h Storer, c Conf) *Resource {
return &Resource{
name: name,
path: name,
schema: s,
validator: validatorFallback{
Validator: s,
fallback: schema.Schema{Fields: schema.Fields{}},
},
storage: storageWrapper{h},
conf: c,
resources: subResources{},
aliases: map[string]url.Values{},
}
}
// Name returns the name of the resource
func (r *Resource) Name() string {
return r.name
}
// Path returns the full path of the resource composed of names of each
// intermediate resources separated by dots (i.e.: res1.res2.res3)
func (r *Resource) Path() string {
return r.path
}
// ParentField returns the name of the field on which the resource is bound to its parent if any.
func (r *Resource) ParentField() string {
return r.parentField
}
// Compile the resource graph and report any error
func (r *Resource) Compile() error {
// Compile schema and panic on any compilation error
if c, ok := r.validator.Validator.(schema.Compiler); ok {
if err := c.Compile(); err != nil {
return fmt.Errorf(": schema compilation error: %s", err)
}
}
for _, r := range r.resources {
if err := r.Compile(); err != nil {
if err.Error()[0] == ':' {
// Check if I'm the direct ancestor of the raised sub-error
return fmt.Errorf("%s%s", r.name, err)
}
return fmt.Errorf("%s.%s", r.name, err)
}
}
return nil
}
// Bind a sub-resource with the provided name. The field parameter defines the parent
// resource's which contains the sub resource id.
//
// users := api.Bind("users", userSchema, userHandler, userConf)
// // Bind a sub resource on /users/:user_id/posts[/:post_id]
// // and reference the user on each post using the "user" field.
// posts := users.Bind("posts", "user", postSchema, postHandler, postConf)
//
// This method will panic an alias or a resource with the same name is already bound
// or if the specified field doesn't exist in the parent resource spec.
func (r *Resource) Bind(name, field string, s schema.Schema, h Storer, c Conf) *Resource {
assertNotBound(name, r.resources, r.aliases)
if f := s.GetField(field); f == nil {
logPanicf(nil, "Cannot bind `%s' as sub-resource: field `%s' does not exist in the sub-resource'", name, field)
}
sr := new(name, s, h, c)
sr.parentField = field
sr.path = r.path + "." + name
r.resources.add(sr)
r.validator.fallback.Fields[name] = schema.Field{
ReadOnly: true,
Validator: connection{
path: "." + name,
},
Params: schema.Params{
"skip": schema.Param{
Description: "The number of items to skip",
Validator: schema.Integer{
Boundaries: &schema.Boundaries{Min: 0},
},
},
"page": schema.Param{
Description: "The page number",
Validator: schema.Integer{
Boundaries: &schema.Boundaries{Min: 1, Max: 1000},
},
},
"limit": schema.Param{
Description: "The number of items to return per page",
Validator: schema.Integer{
Boundaries: &schema.Boundaries{Min: 0, Max: 1000},
},
},
"sort": schema.Param{
Description: "The field(s) to sort on",
Validator: schema.String{},
},
"filter": schema.Param{
Description: "The filter query",
Validator: schema.String{},
},
},
}
return sr
}
// GetResources returns first level resources
func (r *Resource) GetResources() []*Resource {
return r.resources
}
// Alias adds an pre-built resource query on /<resource>/<alias>.
//
// // Add a friendly alias to public posts on /users/:user_id/posts/public
// // (equivalent to /users/:user_id/posts?filter={"public":true})
// posts.Alias("public", url.Values{"where": []string{"{\"public\":true}"}})
//
// This method will panic an alias or a resource with the same name is already bound
func (r *Resource) Alias(name string, v url.Values) {
assertNotBound(name, r.resources, r.aliases)
r.aliases[name] = v
}
// GetAlias returns the alias set for the name if any
func (r *Resource) GetAlias(name string) (url.Values, bool) {
a, found := r.aliases[name]
return a, found
}
// GetAliases returns all the alias names set on the resource
func (r *Resource) GetAliases() []string {
n := make([]string, 0, len(r.aliases))
for a := range r.aliases {
n = append(n, a)
}
return n
}
// Schema returns the resource's schema
func (r *Resource) Schema() schema.Schema {
return r.schema
}
// Validator returns the resource's validator
func (r *Resource) Validator() schema.Validator {
return r.validator
}
// Conf returns the resource's configuration
func (r *Resource) Conf() Conf {
return r.conf
}
// Use attaches an event handler to the resource. This event
// handler must implement on of the resource.*EventHandler interface
// or this method returns an error.
func (r *Resource) Use(e interface{}) error {
return r.hooks.use(e)
}
// Get get one item by its id. If item is not found, ErrNotFound error is returned
func (r *Resource) Get(ctx context.Context, id interface{}) (item *Item, err error) {
if LoggerLevel <= LogLevelDebug && Logger != nil {
defer func(t time.Time) {
Logger(ctx, LogLevelDebug, fmt.Sprintf("%s.Get(%v)", r.path, id), map[string]interface{}{
"duration": time.Since(t),
"error": err,
})
}(time.Now())
}
if err = r.hooks.onGet(ctx, id); err == nil {
item, err = r.storage.Get(ctx, id)
}
r.hooks.onGot(ctx, &item, &err)
return
}
// MultiGet get some items by their id and return them in the same order. If one or more item(s)
// is not found, their slot in the response is set to nil.
func (r *Resource) MultiGet(ctx context.Context, ids []interface{}) (items []*Item, err error) {
if LoggerLevel <= LogLevelDebug && Logger != nil {
defer func(t time.Time) {
Logger(ctx, LogLevelDebug, fmt.Sprintf("%s.MultiGet(%v)", r.path, ids), map[string]interface{}{
"duration": time.Since(t),
"found": len(items),
"error": err,
})
}(time.Now())
}
errs := make([]error, len(ids))
for i, id := range ids {
errs[i] = r.hooks.onGet(ctx, id)
if err == nil && errs[i] != nil {
// first pre-hook error is the global error
err = errs[i]
}
}
// Perform the storage request if none of the pre-hook returned an err
if err == nil {
items, err = r.storage.MultiGet(ctx, ids)
}
var errOverwrite error
for i := range ids {
var _item *Item
if len(items) > i {
_item = items[i]
}
// Give the pre-hook error for this id or global otherwise
_err := errs[i]
if _err == nil {
_err = err
}
r.hooks.onGot(ctx, &_item, &_err)
if errOverwrite == nil && _err != errs[i] {
errOverwrite = _err // apply change done on the first error
}
if _err == nil && len(items) > i && _item != items[i] {
items[i] = _item // apply changes done by hooks if any
}
}
if errOverwrite != nil {
err = errOverwrite
}
if err != nil {
items = nil
}
return
}
// Find calls the Find method on the storage handler with the corresponding pre/post hooks.
func (r *Resource) Find(ctx context.Context, lookup *Lookup, offset, limit int) (list *ItemList, err error) {
return r.find(ctx, lookup, offset, limit, false)
}
// FindWithTotal calls the Find method on the storage handler with the corresponding pre/post hooks.
// If the storage is not able to compute the total, this method will call the Count method on the
// storage. If the storage Find does not compute the total and the Counter interface is not implemented,
// an ErrNotImpemented error is returned.
func (r *Resource) FindWithTotal(ctx context.Context, lookup *Lookup, offset, limit int) (list *ItemList, err error) {
return r.find(ctx, lookup, offset, limit, true)
}
func (r *Resource) find(ctx context.Context, lookup *Lookup, offset, limit int, forceTotal bool) (list *ItemList, err error) {
if LoggerLevel <= LogLevelDebug && Logger != nil {
defer func(t time.Time) {
found := -1
if list != nil {
found = len(list.Items)
}
Logger(ctx, LogLevelDebug, fmt.Sprintf("%s.Find(..., %d, %d)", r.path, offset, limit), map[string]interface{}{
"duration": time.Since(t),
"found": found,
"error": err,
})
}(time.Now())
}
if err = r.hooks.onFind(ctx, lookup, offset, limit); err == nil {
list, err = r.storage.Find(ctx, lookup, offset, limit)
if err == nil && list.Total == -1 && forceTotal {
list.Total, err = r.storage.Count(ctx, lookup)
}
}
r.hooks.onFound(ctx, lookup, &list, &err)
return
}
// Insert implements Storer interface
func (r *Resource) Insert(ctx context.Context, items []*Item) (err error) {
if LoggerLevel <= LogLevelDebug && Logger != nil {
defer func(t time.Time) {
Logger(ctx, LogLevelDebug, fmt.Sprintf("%s.Insert(items[%d])", r.path, len(items)), map[string]interface{}{
"duration": time.Since(t),
"error": err,
})
}(time.Now())
}
if err = r.hooks.onInsert(ctx, items); err == nil {
err = r.storage.Insert(ctx, items)
}
r.hooks.onInserted(ctx, items, &err)
return
}
// Update implements Storer interface
func (r *Resource) Update(ctx context.Context, item *Item, original *Item) (err error) {
if LoggerLevel <= LogLevelDebug && Logger != nil {
defer func(t time.Time) {
Logger(ctx, LogLevelDebug, fmt.Sprintf("%s.Update(%v, %v)", r.path, item.ID, original.ID), map[string]interface{}{
"duration": time.Since(t),
"error": err,
})
}(time.Now())
}
if err = r.hooks.onUpdate(ctx, item, original); err == nil {
err = r.storage.Update(ctx, item, original)
}
r.hooks.onUpdated(ctx, item, original, &err)
return
}
// Delete implements Storer interface
func (r *Resource) Delete(ctx context.Context, item *Item) (err error) {
if LoggerLevel <= LogLevelDebug && Logger != nil {
defer func(t time.Time) {
Logger(ctx, LogLevelDebug, fmt.Sprintf("%s.Delete(%v)", r.path, item.ID), map[string]interface{}{
"duration": time.Since(t),
"error": err,
})
}(time.Now())
}
if err = r.hooks.onDelete(ctx, item); err == nil {
err = r.storage.Delete(ctx, item)
}
r.hooks.onDeleted(ctx, item, &err)
return
}
// Clear implements Storer interface
func (r *Resource) Clear(ctx context.Context, lookup *Lookup) (deleted int, err error) {
if LoggerLevel <= LogLevelDebug && Logger != nil {
defer func(t time.Time) {
Logger(ctx, LogLevelDebug, fmt.Sprintf("%s.Clear(%v)", r.path, lookup), map[string]interface{}{
"duration": time.Since(t),
"deleted": deleted,
"error": err,
})
}(time.Now())
}
if err = r.hooks.onClear(ctx, lookup); err == nil {
deleted, err = r.storage.Clear(ctx, lookup)
}
r.hooks.onCleared(ctx, lookup, &deleted, &err)
return
}