-
Notifications
You must be signed in to change notification settings - Fork 31
/
Resource.js
1074 lines (977 loc) · 31.3 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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const paginate = require('node-paginate-anything');
const jsonpatch = require('fast-json-patch');
const mongodb = require('mongodb');
const moment = require('moment');
const parseRange = require('range-parser');
const debug = {
query: require('debug')('resourcejs:query'),
index: require('debug')('resourcejs:index'),
get: require('debug')('resourcejs:get'),
put: require('debug')('resourcejs:put'),
post: require('debug')('resourcejs:post'),
patch: require('debug')('resourcejs:patch'),
delete: require('debug')('resourcejs:delete'),
virtual: require('debug')('resourcejs:virtual'),
respond: require('debug')('resourcejs:respond'),
};
const utils = require('./utils');
class Resource {
constructor(app, route, modelName, model, options) {
this.app = app;
this.options = options || {};
if (this.options.convertIds === true) {
this.options.convertIds = /(^|\.)_id$/;
}
this.name = modelName.toLowerCase();
this.model = model;
this.modelName = modelName;
this.route = `${route}/${this.name}`;
this.methods = [];
this._swagger = null;
}
/**
* Maintain reverse compatibility.
*
* @param app
* @param method
* @param path
* @param callback
* @param last
* @param options
*/
register(app, method, path, callback, last, options) {
this.app = app;
return this._register(method, path, callback, last, options);
}
/**
* Add a stack processor to be able to execute the middleware independently of ExpressJS.
* Taken from https://github.com/randymized/composable-middleware/blob/master/lib/composable-middleware.js#L27
*
* @param stack
* @return {function(...[*]=)}
*/
stackProcessor(stack) {
return (req, res, done) => {
let layer = 0;
(function next(err) {
const fn = stack[layer++];
if (fn == null) {
done(err);
}
else {
if (err) {
switch (fn.length) {
case 4:
fn(err, req, res, next);
break;
case 2:
fn(err, next);
break;
default:
next(err);
break;
}
}
else {
switch (fn.length) {
case 3:
fn(req, res, next);
break;
case 1:
fn(next);
break;
default:
next();
break;
}
}
}
})();
};
}
/**
* Register a new callback but add before and after options to the middleware.
*
* @param method
* @param path
* @param callback
* @param last
* @param options
*/
_register(method, path, callback, last, options) {
let routeStack = [];
// The before middleware.
if (options && options.before) {
const before = options.before.map((m) => m.bind(this));
routeStack = [...routeStack, ...before];
}
routeStack = [...routeStack, callback.bind(this)];
// The after middleware.
if (options && options.after) {
const after = options.after.map((m) => m.bind(this));
routeStack = [...routeStack, ...after];
}
routeStack = [...routeStack, last.bind(this)];
// Add a fallback error handler.
const error = (err, req, res, next) => {
if (err) {
const status = err.status ? err.status : 400;
res.status(status).json({
status,
message: err.message || err,
});
}
else {
return next();
}
};
routeStack = [...routeStack, error.bind(this)]
// Declare the resourcejs object on the app.
if (!this.app.resourcejs) {
this.app.resourcejs = {};
}
if (!this.app.resourcejs[path]) {
this.app.resourcejs[path] = {};
}
// Add a stack processor so this stack can be executed independently of Express.
this.app.resourcejs[path][method] = this.stackProcessor(routeStack);
// Apply these callbacks to the application.
switch (method) {
case 'get':
this.app.get(path, routeStack);
break;
case 'post':
this.app.post(path, routeStack);
break;
case 'put':
this.app.put(path, routeStack);
break;
case 'patch':
this.app.patch(path, routeStack);
break;
case 'delete':
this.app.delete(path, routeStack);
break;
}
}
/**
* 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
*/
static respond(req, res, next) {
if (req.noResponse || res.headerSent || res.headersSent) {
debug.respond('Skipping');
return next();
}
if (res.resource) {
switch (res.resource.status) {
case 404:
res.status(404).json({
status: 404,
errors: ['Resource not found'],
});
break;
case 400:
case 500:
const errors = {};
for (let property in res.resource.error.errors) {
if (res.resource.error.errors.hasOwnProperty(property)) {
const error = res.resource.error.errors[property];
const { path, name, message } = error;
res.resource.error.errors[property] = { path, name, message };
}
}
res.status(res.resource.status).json({
status: res.resource.status,
message: res.resource.error.message,
errors: res.resource.error.errors,
});
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();
}
static ObjectId(id) {
try {
return (new mongodb.ObjectId(id));
}
catch (e) {
return id;
}
}
/**
* Sets the response that needs to be made and calls the next middleware for
* execution.
*
* @param res
* @param resource
* @param next
*/
static setResponse(res, resource, next) {
res.resource = resource;
next();
}
/**
* Returns the method options for a specific method to be executed.
* @param method
* @param options
* @returns {{}}
*/
static getMethodOptions(method, options) {
if (!options) {
options = {};
}
// If this is already converted to method options then return.
if (options.methodOptions) {
return options;
}
// Uppercase the method.
method = method.charAt(0).toUpperCase() + method.slice(1).toLowerCase();
const methodOptions = { methodOptions: true };
// Find all of the options that may have been passed to the rest method.
const beforeHandlers = options.before ?
(
Array.isArray(options.before) ? options.before : [options.before]
) :
[];
const beforeMethodHandlers = options[`before${method}`] ?
(
Array.isArray(options[`before${method}`]) ? options[`before${method}`] : [options[`before${method}`]]
) :
[];
methodOptions.before = [...beforeHandlers, ...beforeMethodHandlers];
const afterHandlers = options.after ?
(
Array.isArray(options.after) ? options.after : [options.after]
) :
[];
const afterMethodHandlers = options[`after${method}`] ?
(
Array.isArray(options[`after${method}`]) ? options[`after${method}`] : [options[`after${method}`]]
) :
[];
methodOptions.after = [...afterHandlers, ...afterMethodHandlers];
// Expose mongoose hooks for each method.
['before', 'after'].forEach((type) => {
const path = `hooks.${method.toString().toLowerCase()}.${type}`;
utils.set(
methodOptions,
path,
utils.get(options, path, (req, res, item, next) => next())
);
});
// Return the options for this method.
return methodOptions;
}
/**
* _register the whole REST api for this resource.
*
* @param options
* @returns {*|null|HttpPromise}
*/
rest(options) {
return this
.index(options)
.get(options)
.virtual(options)
.put(options)
.patch(options)
.post(options)
.delete(options);
}
/**
* Returns a query parameters fields.
*
* @param req
* @param name
* @returns {*}
*/
static getParamQuery(req, name) {
if (!Object.prototype.hasOwnProperty.call(req.query, name)) {
switch (name) {
case 'populate':
return '';
default:
return null;
}
}
if (name === 'populate' && utils.isObjectLike(req.query[name])) {
return req.query[name];
}
else {
const query = ( Array.isArray(req.query[name]) ? req.query[name].join(',') : req.query[name] );
// Generate string of spaced unique keys
return (query && typeof query === 'string') ? [...new Set(query.match(/[^, ]+/g))].join(' ') : null;
}
}
static getQueryValue(name, value, param, options, selector) {
if (selector && (selector === 'eq' || selector === 'ne') && (typeof value === 'string')) {
const lcValue = value.toLowerCase();
if (lcValue === 'null') {
return null;
}
if (lcValue === '"null"') {
return 'null';
}
if (lcValue === 'true') {
return true;
}
if (lcValue === '"true"') {
return 'true';
}
if (lcValue === 'false') {
return false;
}
if (lcValue === '"false"') {
return 'false';
}
}
if (param.instance === 'Number') {
return parseInt(value, 10);
}
if (param.instance === 'Date') {
const date = moment.utc(value, ['YYYY-MM-DD', 'YYYY-MM', 'YYYY', 'x', moment.ISO_8601], true);
if (date.isValid()) {
return date.toDate();
}
}
// If this is an ID, and the value is a string, convert to an ObjectId.
if (
options.convertIds &&
name.match(options.convertIds) &&
(typeof value === 'string') &&
(mongodb.ObjectId.isValid(value))
) {
try {
value = Resource.ObjectId(value);
}
catch (err) {
console.warn(`Invalid ObjectId: ${value}`);
}
}
return value;
}
/**
* Get the range of items from headers
*
* @param req
* @param size
* @returns {Object}
*/
static getRangeFromHeaders(req, size) {
if (!req.headers.range) {
return null;
}
const range = parseRange(size, req.headers.range);
if (range.type !== 'items') {
return null;
}
return range[0];
}
/**
* Get the find query for the index.
*
* @param req
* @returns {Object}
*/
getFindQuery(req, options, existing) {
const findQuery = {};
options = options || this.options;
// Get the filters and omit the limit, skip, select, sort and populate.
const {limit, skip, select, sort, populate, ...filters} = req.query;
// Sets the findQuery property.
const setFindQuery = function(name, value) {
// Ensure we do not override any existing query parameters.
if (!existing || !existing.hasOwnProperty(name)) {
findQuery[name] = value;
}
};
// Iterate through each filter.
Object.entries(filters).forEach(([name, value]) => {
// Get the filter object.
const filter = utils.zipObject(['name', 'selector'], name.split('__'));
// See if this parameter is defined in our model.
const param = this.model.schema.paths[filter.name.split('.')[0]];
if (param) {
// See if this selector is a regular expression.
if (filter.selector === 'regex') {
// Set the regular expression for the filter.
const parts = value.match(/\/?([^/]+)\/?([^/]+)?/);
let regex = null;
try {
regex = new RegExp(parts[1], (parts[2] || 'i'));
}
catch (err) {
debug.query(err);
regex = null;
}
if (regex) {
setFindQuery(filter.name, regex);
}
return;
} // See if there is a selector.
else if (filter.selector) {
var filterQuery = findQuery[filter.name];
// Init the filter.
if (!filterQuery) {
filterQuery = {};
}
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 (['in', 'nin', 'all'].includes(filter.selector)) {
value = Array.isArray(value) ? value : value.split(',');
value = value.map((item) => Resource.getQueryValue(filter.name, item, param, options, filter.selector));
}
else {
// Set the selector for this filter name.
value = Resource.getQueryValue(filter.name, value, param, options, filter.selector);
}
filterQuery[`$${filter.selector}`] = value;
setFindQuery(filter.name, filterQuery);
return;
}
else {
// Set the find query to this value.
value = Resource.getQueryValue(filter.name, value, param, options, filter.selector);
setFindQuery(filter.name, value);
return;
}
}
if (!options.queryFilter) {
// Set the find query to this value.
setFindQuery(filter.name, value);
}
});
// Return the findQuery.
return findQuery;
}
countQuery(query, pipeline) {
// We cannot use aggregation if mongoose special options are used... like populate.
if (!utils.isEmpty(query._mongooseOptions) || !pipeline) {
return query;
}
const stages = [
{ $match: query.getQuery() },
...pipeline,
{
$group: {
_id : null,
count : { $sum : 1 },
},
},
];
return {
async countDocuments() {
const items = await query.model.aggregate(stages).exec()
return items.length ? items[0].count : 0;
},
};
}
indexQuery(query, pipeline) {
// We cannot use aggregation if mongoose special options are used... like populate.
if (!utils.isEmpty(query._mongooseOptions) || !pipeline) {
return query.lean();
}
const stages = [
{ $match: query.getQuery() },
...pipeline,
];
if (query.options && query.options.sort && !utils.isEmpty(query.options.sort)) {
stages.push({ $sort: query.options.sort });
}
if (query.options && query.options.skip) {
stages.push({ $skip: query.options.skip });
}
if (query.options && query.options.limit) {
stages.push({ $limit: query.options.limit });
}
if (!utils.isEmpty(query._fields)) {
stages.push({ $project: query._fields });
}
return query.model.aggregate(stages);
}
/**
* The index for a resource.
*
* @param options
*/
index(options) {
options = Resource.getMethodOptions('index', options);
this.methods.push('index');
this._register('get', this.route, async (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) {
debug.index('Skipping Resource');
return next();
}
// Get the query object.
let countQuery = req.countQuery || req.modelQuery || req.model || this.model;
const query = req.modelQuery || req.model || this.model;
// Make sure to clone the count query if it is available.
if (typeof countQuery.clone === 'function') {
countQuery = countQuery.clone();
}
// Get the find query.
const findQuery = this.getFindQuery(req, null, query._conditions);
// First get the total count.
try {
const count = await this.countQuery( countQuery.find(findQuery), query.pipeline).countDocuments();
// Get the default limit.
const defaults = { limit: 10, skip: 0 };
const range = Resource.getRangeFromHeaders(req, count);
if (range) {
req.query.limit = req.query.limit || (range.end - range.start + 1);
req.query.skip = req.query.skip || range.start;
// Delete Range header to recreate it below for 'node-paginate-anything' compatibility
delete req.headers.range;
}
let { limit, skip } = req.query
limit = parseInt(limit, 10)
limit = (isNaN(limit) || (limit < 0)) ? defaults.limit : limit
skip = parseInt(skip, 10)
skip = (isNaN(skip) || (skip < 0)) ? defaults.skip : skip
const reqQuery = { limit, skip };
// 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.
const 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;
}
// Next get the items within the index.
const queryExec = query
.find(findQuery)
.limit(reqQuery.limit)
.skip(reqQuery.skip)
.select(Resource.getParamQuery(req, 'select'))
.sort(Resource.getParamQuery(req, 'sort'));
// Only call populate if they provide a populate query.
const populate = Resource.getParamQuery(req, 'populate');
if (populate) {
debug.index(`Populate: ${populate}`);
queryExec.populate(populate);
}
options.hooks.index.before.call(
this,
req,
res,
findQuery,
async () => {
try {
const items = await this.indexQuery(queryExec, query.pipeline).exec();
debug.index(items);
options.hooks.index.after.call(
this,
req,
res,
items,
Resource.setResponse.bind(Resource, res, { status: res.statusCode, item: items }, next)
);
}
catch (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 Resource.setResponse(res, { status: 400, error: err }, next);
}
}
);
}
catch (err) {
debug.index(err);
return Resource.setResponse(res, { status: 400, error: err }, next);
}
}, Resource.respond, options);
return this;
}
/**
* Register the GET method for this resource.
*/
get(options) {
options = Resource.getMethodOptions('get', options);
this.methods.push('get');
this._register('get', `${this.route}/:${this.name}Id`, (req, res, next) => {
// Store the internal method for response manipulation.
req.__rMethod = 'get';
if (req.skipResource) {
debug.get('Skipping Resource');
return next();
}
const query = (req.modelQuery || req.model || this.model).findOne();
const search = { '_id': req.params[`${this.name}Id`] };
// Only call populate if they provide a populate query.
const populate = Resource.getParamQuery(req, 'populate');
if (populate) {
debug.get(`Populate: ${populate}`);
query.populate(populate);
}
options.hooks.get.before.call(
this,
req,
res,
search,
async () => {
try {
let item = await query.where(search).lean().exec()
if (!item) return Resource.setResponse(res, { status: 404 }, next);
return options.hooks.get.after.call(
this,
req,
res,
item,
() => {
// Allow them to only return specified fields.
const select = Resource.getParamQuery(req, 'select');
if (select) {
const newItem = {};
// Always include the _id.
if (item._id) {
newItem._id = item._id;
}
select.split(' ').map(key => {
key = key.trim();
if (item.hasOwnProperty(key)) {
newItem[key] = item[key];
}
});
item = newItem;
}
Resource.setResponse(res, { status: 200, item: item }, next)
}
);
}
catch (err) {
return Resource.setResponse(res, { status: 400, error: err }, next);
}
}
);
}, Resource.respond, options);
return this;
}
/**
* Virtual (GET) method. Returns a user-defined projection (typically an aggregate result)
* derived from this resource
* The virtual method expects at least the path and the before option params to be set.
*/
virtual(options) {
if (!options || !options.path || !options.before) return this;
const path = options.path;
options = Resource.getMethodOptions('virtual', options);
this.methods.push(`virtual/${path}`);
this._register('get', `${this.route}/virtual/${path}`, async (req, res, next) => {
// Store the internal method for response manipulation.
req.__rMethod = 'virtual';
if (req.skipResource) {
debug.virtual('Skipping Resource');
return next();
}
const query = req.modelQuery || req.model;
if (!query) return Resource.setResponse(res, { status: 404 }, next);
try {
const item = await query.exec()
if (!item) return Resource.setResponse(res, { status: 404 }, next);
return Resource.setResponse(res, { status: 200, item }, next);
}
catch (err) {
return Resource.setResponse(res, { status: 400, error: err }, next)
}
}, Resource.respond, options);
return this;
}
/**
* Post (Create) a new item
*/
post(options) {
options = Resource.getMethodOptions('post', options);
this.methods.push('post');
this._register('post', this.route, (req, res, next) => {
// Store the internal method for response manipulation.
req.__rMethod = 'post';
if (req.skipResource) {
debug.post('Skipping Resource');
return next();
}
const Model = req.model || this.model;
const model = new Model(req.body);
options.hooks.post.before.call(
this,
req,
res,
req.body,
async () => {
try {
const writeOptions = req.writeOptions || {};
const item = await model.save(writeOptions)
debug.post(item);
// Trigger any after hooks before responding.
return options.hooks.post.after.call(
this,
req,
res,
item,
Resource.setResponse.bind(Resource, res, { status: 201, item }, next)
);
}
catch (err) {
debug.post(err);
return Resource.setResponse(res, { status: 400, error: err }, next);
}
}
);
}, Resource.respond, options);
return this;
}
/**
* Put (Update) a resource.
*/
put(options) {
options = Resource.getMethodOptions('put', options);
this.methods.push('put');
this._register('put', `${this.route}/:${this.name}Id`, async (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
const { __v, ...update} = req.body;
const query = req.modelQuery || req.model || this.model;
try {
const item = await query.findOne({ _id: Resource.ObjectId(req.params[`${this.name}Id`]) })
if (!item) {
debug.put(`No ${this.name} found with ${this.name}Id: ${req.params[`${this.name}Id`]}`);
return Resource.setResponse(res, { status: 404 }, next);
}
item.set(update);
options.hooks.put.before.call(
this,
req,
res,
item,
async () => {
const writeOptions = req.writeOptions || {};
try {
const savedItem = await item.save(writeOptions);
return options.hooks.put.after.call(
this,
req,
res,
savedItem,
Resource.setResponse.bind(Resource, res, { status: 200, item: savedItem }, next)
);
}
catch (err) {
debug.put(err);
return Resource.setResponse(res, { status: 400, error: err }, next);
}
});
}
catch (err) {
debug.put(err);
return Resource.setResponse(res, { status: 400, error: err }, next);
}
}, Resource.respond, options);
return this;
}
/**
* Patch (Partial Update) a resource.
*/
patch(options) {
options = Resource.getMethodOptions('patch', options);
this.methods.push('patch');
this._register('patch', `${this.route}/:${this.name}Id`, async (req, res, next) => {
// Store the internal method for response manipulation.
req.__rMethod = 'patch';
if (req.skipResource) {
debug.patch('Skipping Resource');
return next();
}
const query = req.modelQuery || req.model || this.model;
const writeOptions = req.writeOptions || {};
try {
const item = await query.findOne({ '_id': req.params[`${this.name}Id`] });
if (!item) return Resource.setResponse(res, { status: 404, error: err }, next);
// Ensure patches is an array
const patches = [].concat(req.body);
let patchFail = null;
try {
patches.forEach((patch) => {
if (patch.op === 'test') {
patchFail = patch;
const success = jsonpatch.applyOperation(item, patch, true);
if (!success || !success.test) {
return Resource.setResponse(res, {
status: 412,
name: 'Precondition Failed',
message: 'A json-patch test op has failed. No changes have been applied to the document',
item,
patch,
}, next);
}
}
});
jsonpatch.applyPatch(item, patches, true);
}
catch (err) {
switch (err.name) {
// Check whether JSON PATCH error
case 'TEST_OPERATION_FAILED':
return Resource.setResponse(res, {
status: 412,
name: 'Precondition Failed',
message: 'A json-patch test op has failed. No changes have been applied to the document',
item,
patch: patchFail,
}, next);
case 'SEQUENCE_NOT_AN_ARRAY':
case 'OPERATION_NOT_AN_OBJECT':
case 'OPERATION_OP_INVALID':
case 'OPERATION_PATH_INVALID':
case 'OPERATION_FROM_REQUIRED':
case 'OPERATION_VALUE_REQUIRED':
case 'OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED':
case 'OPERATION_PATH_CANNOT_ADD':
case 'OPERATION_PATH_UNRESOLVABLE':
case 'OPERATION_FROM_UNRESOLVABLE':
case 'OPERATION_PATH_ILLEGAL_ARRAY_INDEX':
case 'OPERATION_VALUE_OUT_OF_BOUNDS':
err.errors = [{
name: err.name,
message: err.toString(),
}];
return Resource.setResponse(res, {
status: 400,
item,
error: err,
}, next);
// Something else than JSON PATCH
default:
return Resource.setResponse(res, { status: 400, item, error: err }, next);
}
}
try {
const savedItem = await item.save(writeOptions);
return Resource.setResponse(res, { status: 200, item: savedItem }, next);
}
catch (err) {
return Resource.setResponse(res, { status: 400, error: err }, next);
}
}
catch(err) {
return Resource.setResponse(res, { status: 400, error: err }, next)
}
}, Resource.respond, options);
return this;
}
/**
* Delete a resource.
*/
delete(options) {
options = Resource.getMethodOptions('delete', options);