forked from travist/resourcejs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Resource.js
642 lines (564 loc) · 19.9 KB
/
Resource.js
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
var _ = require('lodash');
var paginate = require('node-paginate-anything');
var jsonpatch = require('fast-json-patch');
var middleware = require( 'composable-middleware');
var debug = {
query: require('debug')('resourcejs:query'),
index: require('debug')('resourcejs:index'),
put: require('debug')('resourcejs:put'),
post: require('debug')('resourcejs:post'),
delete: require('debug')('resourcejs:delete'),
respond: require('debug')('resourcejs:respond')
};
module.exports = function(app, route, modelName, model) {
// Create the name of the resource.
var name = modelName.toLowerCase();
// Return the object that defines this resource.
return {
/**
* The model for this resource.
*/
model: model,
/**
* The name of the model.
*/
modelName: modelName,
/**
* The name of this resource.
*/
name: name,
/**
* The route for this model.
*/
route: route + '/' + name,
/**
* The methods that are exposed to this resource.
*/
methods: [],
/**
* The swagger cache.
*/
__swagger: null,
/**
* Register a new callback but add before and after options to the middleware.
*
* @param app
* @param method
* @param path
* @param callback
* @param last
* @param options
*/
register: function(app, method, path, callback, last, options) {
var mw = middleware();
var len, i;
// The before middleware.
if (options && options.before) {
var before = [].concat(options.before);
for (len = before.length, i=0; i<len; ++i) {
mw.use(before[i].bind(this));
}
}
mw.use(callback.bind(this));
// The after middleware.
if (options && options.after) {
var after = [].concat(options.after);
for (len = after.length, i=0; i<len; ++i) {
mw.use(after[i].bind(this));
}
}
mw.use(last.bind(this));
// Declare the resourcejs object on the app.
if (!app.resourcejs) {
app.resourcejs = {};
}
if (!app.resourcejs[path]) {
app.resourcejs[path] = {};
}
// Add these methods to resourcejs object in the app.
app.resourcejs[path][method] = mw;
// Apply these callbacks to the application.
app[method](path, mw);
},
/**
* Sets the different responses and calls the next middleware for
* execution.
*
* @param res
* The response to send to the client.
* @param next
* The next middleware
*/
respond: function(req, res, next) {
if (req.noResponse || res.headerSent || res.headersSent) {
debug.respond('Skipping');
return next();
}
if (res.resource) {
switch (res.resource.status) {
case 400:
res.status(400).json({
status: 400,
message: res.resource.error.message,
errors: _.mapValues(res.resource.error.errors, function(error) {
return _.pick(error, 'path', 'name', 'message');
})
});
break;
case 404:
res.status(404).json({
status: 404,
errors: ['Resource not found']
});
break;
case 500:
res.status(500).json({
status: 500,
message: res.resource.error.message,
errors: _.mapValues(res.resource.error.errors, function(error) {
return _.pick(error, 'path', 'name', 'message');
})
});
break;
case 204:
// Convert 204 into 200, to preserve the empty result set.
// Update the empty response body based on request method type.
debug.respond('204 -> ' + req.__rMethod);
switch (req.__rMethod) {
case 'index':
res.status(200).json([]);
break;
default:
res.status(200).json({});
break;
}
break;
default:
res.status(res.resource.status).json(res.resource.item);
break;
}
}
next();
},
/**
* Sets the response that needs to be made and calls the next middleware for
* execution.
*
* @param res
* @param resource
* @param next
*/
setResponse: function(res, resource, next) {
res.resource = resource;
next();
},
/**
* Returns the method options for a specific method to be executed.
* @param method
* @param options
* @returns {{}}
*/
getMethodOptions: function(method, options) {
if (!options) return {};
// Uppercase the method.
method = method.charAt(0).toUpperCase() + method.slice(1).toLowerCase();
var methodOptions = {};
// Find all of the options that may have been passed to the rest method.
if (options.before) {
methodOptions.before = options.before;
}
else if (options.hasOwnProperty('before' + method)) {
methodOptions.before = options['before' + method];
}
if (options.after) {
methodOptions.after = options.after;
}
else if (options.hasOwnProperty('after' + method)) {
methodOptions.after = options['after' + method];
}
// Return the options for this method.
return methodOptions;
},
/**
* Register the whole REST api for this resource.
*
* @param options
* @returns {*|null|HttpPromise}
*/
rest: function(options) {
return this
.index(this.getMethodOptions('index', options))
.get(this.getMethodOptions('get', options))
.virtual(this.getMethodOptions('virtual', options))
.put(this.getMethodOptions('put', options))
.patch(this.getMethodOptions('patch', options))
.post(this.getMethodOptions('post', options))
.delete(this.getMethodOptions('delete', options));
},
/**
* Returns a query parameters fields.
*
* @param req
* @param name
* @returns {*}
*/
getParamQuery: function(req, name) {
if (!req.query.hasOwnProperty(name)) {
switch (name) {
case 'populate':
return '';
default:
return null;
}
}
return _.words(req.query[name], /[^, ]+/g).join(' ');
},
/**
* Get the find query for the index.
*
* @param req
* @returns {Object}
*/
getFindQuery: function(req) {
var findQuery = {};
// Get the filters and omit the limit, skip, select, and sort.
var filters = _.omit(req.query, 'limit', 'skip', 'select', 'sort', 'populate');
// Iterate through each filter.
_.each(filters, function(value, name) {
// Get the filter object.
var filter = _.zipObject(['name', 'selector'], name.split('__'));
// See if this parameter is defined in our model.
var param = this.model.schema.paths[filter.name.split('.')[0]];
if (param) {
// See if there is a selector.
if (filter.selector) {
// See if this selector is a regular expression.
if (filter.selector === 'regex') {
// Set the regular expression for the filter.
var parts = value.match(/\/?([^/]+)\/?([^/]+)?/);
var regex = null;
try {
regex = new RegExp(parts[1], (parts[2] || 'i'));
}
catch (err) {
debug.query(err);
regex = null;
}
if (regex) {
findQuery[filter.name] = regex;
}
return;
}
else {
// Init the filter.
if (!findQuery.hasOwnProperty(filter.name)) {
findQuery[filter.name] = {};
}
if (filter.selector === 'exists') {
value = ((value === 'true') || (value === '1')) ? true : value;
value = ((value === 'false') || (value === '0')) ? false : value;
value = !!value;
}
// Special case for in filter with multiple values.
else if ((_.indexOf(['in', 'nin'], filter.selector) !== -1)) {
value = value.split(',');
_.map(value, function(item) {
return (param.instance === 'Number')
? parseInt(item, 10)
: item;
});
}
else {
// Set the selector for this filter name.
value = (param.instance === 'Number')
? parseInt(value, 10)
: value;
}
findQuery[filter.name]['$' + filter.selector] = value;
return;
}
}
else {
// Set the find query to this value.
value = (param.instance === 'Number')
? parseInt(value, 10)
: value;
findQuery[filter.name] = value;
return;
}
}
// Set the find query to this value.
findQuery[filter.name] = value;
}.bind(this));
// Return the findQuery.
return findQuery;
},
/**
* The index for a resource.
*
* @param options
*/
index: function(options) {
this.methods.push('index');
this.register(app, 'get', this.route, function(req, res, next) {
// Store the internal method for response manipulation.
req.__rMethod = 'index';
// Allow before handlers the ability to disable resource CRUD.
if (req.skipResource) { return next(); }
// Get the find query.
var findQuery = this.getFindQuery(req);
// Get the query object.
var countQuery = req.countQuery || req.modelQuery || this.model;
var query = req.modelQuery || this.model;
// First get the total count.
countQuery.find(findQuery).count(function(err, count) {
if (err) {
debug.index(err);
return this.setResponse(res, {status: 500, error: err}, next);
}
// Get the default limit.
var defaults = {limit: 10, skip: 0};
var reqQuery = _.mapValues(_.defaults(_.pick(req.query, 'limit', 'skip'), defaults), function(value, key) {
value = parseInt(value, 10);
return (isNaN(value) || (value < 0)) ? defaults[key] : value;
});
// If a skip is provided, then set the range headers.
if (reqQuery.skip && !req.headers.range) {
req.headers['range-unit'] = 'items';
req.headers.range = reqQuery.skip + '-' + (reqQuery.skip + (reqQuery.limit - 1));
}
// Get the page range.
var pageRange = paginate(req, res, count, reqQuery.limit) || {
limit: reqQuery.limit,
skip: reqQuery.skip
};
// Make sure that if there is a range provided in the headers, it takes precedence.
if (req.headers.range) {
reqQuery.limit = pageRange.limit;
reqQuery.skip = pageRange.skip;
}
// Get the populate parameter.
var populate = this.getParamQuery(req, 'populate');
if (populate) {
debug.index('Populate: ' + populate);
}
// Next get the items within the index.
var queryExec = query
.find(findQuery)
.limit(reqQuery.limit)
.skip(reqQuery.skip)
.select(this.getParamQuery(req, 'select'))
.sort(this.getParamQuery(req, 'sort'));
// Only call populate if they provide a populate query.
if (populate) {
queryExec = queryExec.populate(populate);
}
// Execute the query.
queryExec.exec(function(err, items) {
if (err) {
debug.index(err);
debug.index(err.name);
if (err.name == 'CastError' && populate) {
err.message = 'Cannot populate "' + populate + '" as it is not a reference in this resource'
debug.index(err.message);
}
return this.setResponse(res, {status: 500, error: err}, next);
}
debug.index(items);
return this.setResponse(res, {status: res.statusCode, item: items}, next);
}.bind(this));
}.bind(this));
}, this.respond.bind(this), options);
return this;
},
/**
* Register the GET method for this resource.
*/
get: function(options) {
this.methods.push('get');
this.register(app, 'get', this.route + '/:' + this.name + 'Id', function(req, res, next) {
// Store the internal method for response manipulation.
req.__rMethod = 'get';
if (req.skipResource) {
return next();
}
var query = req.modelQuery || this.model;
query.findOne({'_id': req.params[this.name + 'Id']}, function(err, item) {
if (err) return this.setResponse(res, {status: 500, error: err}, next);
if (!item) return this.setResponse(res, {status: 404}, next);
return this.setResponse(res, {status: 200, item: item}, next);
}.bind(this));
}, this.respond.bind(this), options);
return this;
},
/**
* Virtual (GET) method. Returns a user-defined projection (typically an aggregate result)
* derived from this resource
*/
virtual: function(options) {
this.methods.push('virtual');
var path = (options.path === undefined) ? this.path : options.path;
this.register(app, 'get', this.route + '/virtual/' + path, function(req, res, next) {
// Store the internal method for response manipulation.
req.__rMethod = 'virtual';
if (req.skipResource) { return next(); }
var query = req.modelQuery;
query.exec(function(err, item) {
if (err) return this.setResponse(res, {status: 500, error: err}, next);
if (!item) return this.setResponse(res, {status: 404}, next);
return this.setResponse(res, {status: 200, item: item}, next);
}.bind(this));
}, this.respond.bind(this), options);
return this;
},
/**
* Post (Create) a new item
*/
post: function(options) {
this.methods.push('post');
this.register(app, 'post', this.route, function(req, res, next) {
// Store the internal method for response manipulation.
req.__rMethod = 'post';
if (req.skipResource) {
debug.post('Skipping Resource');
return next();
}
this.model.create(req.body, function(err, item) {
if (err) {
debug.post(err);
return this.setResponse(res, {status: 400, error: err}, next);
}
debug.post(item);
return this.setResponse(res, {status: 201, item: item}, next);
}.bind(this));
}, this.respond.bind(this), options);
return this;
},
/**
* Put (Update) a resource.
*/
put: function(options) {
this.methods.push('put');
this.register(app, 'put', this.route + '/:' + this.name + 'Id', function(req, res, next) {
// Store the internal method for response manipulation.
req.__rMethod = 'put';
if (req.skipResource) {
debug.put('Skipping Resource');
return next();
}
// Remove __v field
var update = _.omit(req.body, '__v');
var query = req.modelQuery || this.model;
query.findOne({_id: req.params[this.name + 'Id']}, function(err, item) {
if (err) {
debug.put(err);
return this.setResponse(res, {status: 500, error: err}, next);
}
if (!item) {
debug.put('No ' + this.name + ' found with ' + this.name + 'Id: ' + req.params[this.name + 'Id']);
return this.setResponse(res, {status: 404}, next);
}
item.set(update);
item.save(function(err, item) {
if (err) {
debug.put(err);
return this.setResponse(res, {status: 500, error: err}, next);
}
debug.put(JSON.stringify(item));
return this.setResponse(res, {status: 200, item: item}, next);
}.bind(this));
}.bind(this));
}, this.respond.bind(this), options);
return this;
},
/**
* Patch (Partial Update) a resource.
*/
patch: function(options) {
this.methods.push('patch');
this.register(app, 'patch', this.route + '/:' + this.name + 'Id', function(req, res, next) {
// Store the internal method for response manipulation.
req.__rMethod = 'patch';
if (req.skipResource) { return next(); }
var query = req.modelQuery || this.model;
query.findOne({'_id': req.params[this.name + 'Id']}, function(err, item) {
if (err) return this.setResponse(res, {status: 500, error: err}, next);
if (!item) return this.setResponse(res, {status: 404, error: err}, next);
var patches = req.body;
try {
for (var len = patches.length, i=0; i<len; ++i) {
var patch = patches[i];
if(patch.op=='test'){
var success = jsonpatch.apply(item, [].concat(patch), true);
if(!success){
return this.setResponse(res, {
status: 412,
name: 'Precondition Failed',
message: 'A json-patch test op has failed. No changes have been applied to the document',
item: item,
patch: patch
}, next);
}
}
}
jsonpatch.apply(item, patches, true);
} catch(err) {
if (err) return this.setResponse(res, {status: 500, item: item, error: err}, next);
}
item.save(function (err, item) {
if (err) return this.setResponse(res, {status: 400, error: err}, next);
return this.setResponse(res, {status: 200, item: item}, next);
}.bind(this));
}.bind(this));
}, this.respond.bind(this), options);
return this;
},
/**
* Delete a resource.
*/
delete: function(options) {
this.methods.push('delete');
this.register(app, 'delete', this.route + '/:' + this.name + 'Id', function(req, res, next) {
// Store the internal method for response manipulation.
req.__rMethod = 'delete';
if (req.skipResource) {
debug.delete('SKipping Resource');
return next();
}
var query = req.modelQuery || this.model;
query.findOne({'_id': req.params[this.name + 'Id']}, function(err, item) {
if (err) {
debug.delete(err);
return this.setResponse(res, {status: 500, error: err}, next);
}
if (!item) {
debug.delete('No ' + this.name + ' found with ' + this.name + 'Id: ' + req.params[this.name + 'Id']);
return this.setResponse(res, {status: 404, error: err}, next);
}
if (req.skipDelete) {
return this.setResponse(res, {status: 204, item: item, deleted: true}, next);
}
query.remove({_id: item._id}, function(err) {
if (err) {
debug.delete(err);
return this.setResponse(res, {status: 400, error: err}, next);
}
debug.delete(item);
return this.setResponse(res, {status: 204, item: item, deleted: true}, next);
}.bind(this));
}.bind(this));
}, this.respond.bind(this), options);
return this;
},
/**
* Returns the swagger definition for this resource.
*/
swagger: function(resetCache) {
resetCache = resetCache || false;
if (!this.__swagger || resetCache) {
this.__swagger = require('./Swagger')(this);
}
return this.__swagger;
}
};
};