forked from premku70/swagger-mongoose-crud
-
Notifications
You must be signed in to change notification settings - Fork 3
/
crud.controller.js
1017 lines (976 loc) · 36.9 KB
/
crud.controller.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';
var _ = require('lodash');
var BaseController = require('./base.controller');
var params = require('./swagger.params.map');
var mongoose = require('mongoose');
const transactionOptions = {
readPreference: 'primary',
readConcern: { level: 'majority' },
writeConcern: { w: 'majority' }
}
/**
* Constructor function for CrudController.
* @classdesc Controller for basic CRUD operations on mongoose models.
* Uses the passed id name as the request parameter id to identify models.
* @constructor
* @inherits BaseController
* @param {Model} model - The mongoose model to operate on
* @param {String} [idName] - The name of the id request parameter to use
*/
function CrudController(model, logger, defaultFilter, permanentDeleteData) {
// call super constructor
BaseController.call(this, this);
// set the model instance to work on
this.model = model;
this.logger = logger;
this.defaultFilter = defaultFilter ? defaultFilter : {};
this.defaultFilter = this.FilterParse(defaultFilter);
this.permanentDeleteData = permanentDeleteData;
// set id name if defined, defaults to 'id'
this.omit = [];
_.bindAll(this);
}
function debugLogReq(req, logger) {
var ob = _.pick(req, ['baseUrl', 'hostname', 'params', 'path', 'query']);
logger.trace("Getting Request::" + JSON.stringify(ob));
}
async function handleSession(session, abortTransaction) {
if (abortTransaction) await session.abortTransaction();
else await session.commitTransaction();
session.endSession();
}
async function getMongoDbVersion() {
return (await mongoose.connection.db.admin().serverInfo()).version;
}
async function isTransactionSupported() {
let version = await getMongoDbVersion();
let minorVersion = parseFloat(version.substring(0, version.lastIndexOf('.')));
return minorVersion >= 4.2;
}
function saveDocument(doc, req, docIds, model, self, documents) {
let docModel = new model(doc);
if (docIds.indexOf(docModel._id) < 0) {
return docModel.save(req)
.then(_d => {
return { statusCode: 200, message: _d }
})
.catch(err => {
return { statusCode: 400, message: { message: err.message } }
})
}
else {
let _document = documents.find(_d => _d._id == doc._id);
let updated = _.mergeWith(_document, doc, self._customizer);
updated = new self.model(updated);
Object.keys(doc).forEach(el => updated.markModified(el));
return updated.save(req)
.then(_d => {
return { statusCode: 200, message: _d }
})
.catch(err => {
return { statusCode: 400, message: { message: err.message } }
})
}
}
function createDocument(model, body, req, documents, self) {
let args = [];
if (Array.isArray(body)) {
args = body;
} else {
args.push(body);
}
// let savePromise = [];
let docIds = documents.map(doc => doc._id);
let results = [];
return args.reduce((prev, doc) => {
return prev.then(async (e) => {
const result = await saveDocument(doc, req, docIds, model, self, documents);
results.push(result);
});
}, Promise.resolve(null)).then(() => {
return Promise.resolve(results);
});
// args.forEach(doc => {
// savePromise.push(saveDocument(doc, req, docIds, model, self, documents));
// });
// return Promise.all(savePromise);
}
function removeDocument(doc, req, type) {
return new Promise(resolve => {
if (type == "markAsDeleted") {
doc._metadata.deleted = true;
doc.save(req)
.then(doc => {
resolve(doc);
})
.catch(err => resolve(null));
} else {
doc.remove(req)
.then(() => {
resolve(doc.toObject());
})
.catch(err => resolve(null));
}
});
}
function bulkRemove(self, req, res, type) {
var reqParams = params.map(req);
debugLogReq(req, self.logger);
let document = null;
var ids = reqParams['id'] ? reqParams['id'].split(',') : [];
return self.model.find({
'_id': { "$in": ids },
'_metadata.deleted': false
})
.then(docs => {
if (!docs) {
return [];
}
let removePromise = docs.map(doc => removeDocument(doc, req, type));
return Promise.all(removePromise);
})
.then((removedDocs) => {
removedDocs = removedDocs.filter(doc => doc != null);
let removedIds = removedDocs.map(doc => doc._id);
var logObject = {
'operation': 'Delete',
'user': req.user ? req.user.username : req.headers['masterName'],
'_id': removedIds,
'timestamp': new Date()
};
self.logger.trace(JSON.stringify(logObject));
let docsNotRemoved = _.difference(_.uniq(ids), removedIds);
if (_.isEmpty(docsNotRemoved))
return self.Okay(res, {});
else {
throw new Error("Could not delete document with id " + docsNotRemoved);
}
})
.catch(err => {
return self.Error(res, err);
});
}
let invalidAggregationKeys = [
'$graphLookup',
'$lookup',
'$merge',
'$out',
'$currentOp',
'$collStats',
'$indexStats',
'$planCacheStats',
'$listLocalSessions',
'$listSessions'
];
function validateAggregation(body) {
if (!body) return true;
if (Array.isArray(body)) {
return body.every(_b => validateAggregation(_b));
}
if (body.constructor == {}.constructor) {
return Object.keys(body).every(_k => {
let flag = invalidAggregationKeys.indexOf(_k) === -1;
if (!flag) throw new Error(_k + ' is restricted.');
return flag && validateAggregation(body[_k]);
});
}
return true;
}
CrudController.prototype = {
/**
* Set our own constructor property for instanceof checks
* @private
*/
constructor: CrudController,
/**
* The model instance to perform operations with
* @type {MongooseModel}
*/
model: null,
/**
* The id parameter name
* @type {String}
* @default 'id'
*/
idName: 'id',
/**
* Flag indicating whether the index query should be performed lean
* @type {Boolean}
* @default true
*/
lean: true,
/**
* Array of fields passed to the select statement of the index query.
* The array is joined with a whitespace before passed to the select
* method of the controller model.
* @type {Array}
* @default The empty Array
*/
select: [],
/**
* Array of fields that should be omitted from the query.
* The property names are stripped from the query object.
* @type {Array}
* @default The empty Array
*/
omit: [],
/**
* Name of the property (maybe a virtual) that should be returned
* (send as response) by the methods.
* @type {String}
* @default The empty String
*/
defaultReturn: '',
debugLogger: function (doc, body) {
var intersection = _.pick(doc, _.keysIn(body));
this.logger.trace('Object with id :-' + doc._id + ' has been updated, old values:-' + JSON.stringify(intersection) + ' new values:- ' + JSON.stringify(body));
},
/**
* Default Data handlers for Okay Response
* @type {function}
* @default Okay response.
*/
Okay: function (res, data) {
// this.logger.debug('Sending Response:: ' + JSON.stringify(data))
res.status(200).json(data);
},
/**
* Default Data handlers for Okay Response
* @type {function}
* @default Okay response.
*/
NotFound: function (res) {
res.status(404).send();
},
IsString: function (val) {
return val && val.constructor.name === 'String';
},
CreateRegexp: function (str) {
if (str.charAt(0) === '/' &&
str.charAt(str.length - 1) === '/') {
var text = str.substr(1, str.length - 2).replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
return new RegExp(text, 'i');
} else {
return str;
}
},
IsArray: function (arg) {
return arg && arg.constructor.name === 'Array';
},
IsObject: function (arg) {
return arg && arg.constructor.name === 'Object';
},
ResolveArray: function (arr) {
var self = this;
for (var x = 0; x < arr.length; x++) {
if (self.IsObject(arr[x])) {
arr[x] = self.FilterParse(arr[x]);
} else if (self.IsArray(arr[x])) {
arr[x] = self.ResolveArray(arr[x]);
} else if (self.IsString(arr[x])) {
arr[x] = self.CreateRegexp(arr[x]);
}
}
return arr;
},
/*
* Takes the filter field and parses it to a JSON object
* @type {function}
*
*/
FilterParse: function (filterParsed) {
var self = this;
for (var key in filterParsed) {
if (self.IsString(filterParsed[key])) {
filterParsed[key] = self.CreateRegexp(filterParsed[key]);
} else if (self.IsArray(filterParsed[key])) {
filterParsed[key] = self.ResolveArray(filterParsed[key]);
} else if (self.IsObject(filterParsed[key])) {
filterParsed[key] = self.FilterParse(filterParsed[key]);
}
}
return filterParsed;
},
/**
* Default Data handlers for Okay Response
* @type {function}
* @default Okay response.
*/
Error: function (res, err) {
if (err.errors) {
var errors = [];
Object.keys(err.errors).forEach(el => errors.push(err.errors[el].message));
res.status(400).json({
message: errors
});
// this.logger.debug('Sending Response:: ' + JSON.stringify({ message: errors }));
} else {
if (!res.headersSent) {
res.status(400).json({
message: [err.message]
});
}
}
},
/**
* Get a count of results matching a particular filter criteria.
* @param {IncomingMessage} req - The request message object
* @param {ServerResponse} res - The outgoing response object the result is set to
*/
_count: function (req, res) {
var self = this;
var reqParams = params.map(req);
var filter = reqParams['filter'] ? reqParams.filter : {};
debugLogReq(req, this.logger);
if (typeof filter === 'string') {
try {
filter = JSON.parse(filter);
filter = self.FilterParse(filter);
} catch (err) {
this.logger.error('Failed to parse filter :' + err);
filter = {};
}
}
filter = _.assign({}, self.defaultFilter, filter);
if (this.omit.length > 0) {
filter = _.omit(filter, this.omit);
}
if (!this.permanentDeleteData)
filter['_metadata.deleted'] = false;
return this.model
.find(filter)
.count()
.exec()
.then(result => self.Okay(res, result))
.catch(err => {
return self.Error(res, err);
});
},
/**
* Get a list of documents. If a request query is passed it is used as the
* query object for the find method.
* @param {IncomingMessage} req - The request message object
* @param {ServerResponse} res - The outgoing response object the result is set to
* @param {Object} options - The options to manipulate response before sending.
* @returns {ServerResponse} Array of all documents for the {@link CrudController#model} model
* or the empty Array if no documents have been found
*/
_index: function (req, res, options) {
var reqParams = params.map(req);
debugLogReq(req, this.logger);
var filter = reqParams['filter'] ? reqParams.filter : {};
var sort = reqParams['sort'] ? {} : {
'_metadata.lastUpdated': -1
};
reqParams['sort'] ? reqParams.sort.split(',').map(el => el.split('-').length > 1 ? sort[el.split('-')[1]] = -1 : sort[el.split('-')[0]] = 1) : null;
var select = reqParams['select'] ? reqParams.select.split(',') : [];
var page = reqParams['page'] ? +reqParams.page : 1;
var count = reqParams['count'] ? +reqParams.count : 10;
var search = reqParams['search'] ? reqParams.search : null;
var metadata = req.query['metadata'] ? req.query.metadata.toLowerCase() == 'true' : false;
var skip = count * (page - 1);
var self = this;
if (typeof filter === 'string') {
try {
filter = JSON.parse(filter);
filter = self.FilterParse(filter);
} catch (err) {
this.logger.error('Failed to parse filter :' + err);
filter = {};
}
}
filter = _.assign({}, self.defaultFilter, filter);
if (this.omit.length) {
filter = _.omit(filter, this.omit);
}
if (!this.permanentDeleteData)
filter['_metadata.deleted'] = false;
if (search) {
filter['$text'] = { '$search': search };
}
var query = this.model.find(filter);
if (this.lean) {
query.lean();
}
if (this.select.length || select.length) {
var union = this.select.concat(select);
query.select(union.join(' '));
}
if (count == -1) query.sort(sort)
else query.skip(skip).limit(count).sort(sort);
let docs = null;
let matched = 0, totalCount = 0;
let resBody = {};
return query.exec()
.then(documents => {
docs = documents;
let promise = Promise.resolve();
if (metadata) {
promise = this.model.count(filter)
.then(_c => {
matched = _c;
return this.model.count()
})
.then(_t => {
totalCount = _t;
})
}
return promise;
})
.then(() => {
if (metadata) {
resBody = {
_metadata: {
page,
count,
matched,
totalCount
},
data: docs
};
} else {
resBody = docs;
}
if (options && options.resHandler && typeof options.resHandler == 'function') {
let resVal = options.resHandler(undefined, res, resBody, 200);
if (!res.headersSent) {
if (resVal instanceof Promise) {
return resVal.then(_docs => self.Okay(res, _docs))
} else {
return self.Okay(res, resVal)
}
}
return;
}
return self.Okay(res, resBody);
})
.catch(err => {
if (options && options.resHandler && typeof options.resHandler == 'function') {
let resVal = options.resHandler(err, res);
if (!res.headersSent) {
if (resVal instanceof Promise) {
return resVal.then(_docs => self.Error(res, _docs ? docs : err))
} else {
return self.Error(res, resVal ? resVal : err)
}
}
return;
}
return self.Error(res, err);
});
},
/**
* Get a single document. The requested document id is read from the request parameters
* by using the {@link CrudController#idName} property.
* @param {IncomingMessage} req - The request message object the id is read from
* @param {ServerResponse} res - The outgoing response object
* @param {Object} options - The options to manipulate response before sending.
* @returns {ServerResponse} A single document or NOT FOUND if no document has been found
*/
_show: function (req, res, options) {
var self = this;
debugLogReq(req, this.logger);
var reqParams = params.map(req);
var select = reqParams['select'] ? reqParams.select.split(',') : []; //Comma seprated fileds list
var query = this.model.findOne({
'_id': reqParams['id'],
'_metadata.deleted': false
});
if (select.length > 0) {
query = query.select(select.join(' '));
}
return query.exec()
.then((document) => {
if (options && options.resHandler && typeof options.resHandler == 'function') {
let resVal = options.resHandler(undefined, res, document ? document : "", document ? 200 : 404);
if (!res.headersSent) {
if (resVal instanceof Promise) {
return resVal.then(_docs => self.Okay(res, _docs))
} else {
return self.Okay(res, resVal)
}
}
return;
}
if (!document) {
return self.NotFound(res);
} else {
return self.Okay(res, self.getResponseObject(document));
}
})
.catch(err => {
if (options && options.resHandler && typeof options.resHandler == 'function') {
let resVal = options.resHandler(err, res);
if (!res.headersSent) {
if (resVal instanceof Promise) {
return resVal.then(_docs => self.Error(res, _docs ? docs : err))
} else {
return self.Error(res, resVal ? resVal : err)
}
}
return;
}
return self.Error(res, err);
});
},
/**
* Runs aggregation on a collection. The API need request body as aggregation body.
* @param {IncomingMessage} req - The request message object
* @param {ServerResponse} res - The outgoing response object the result is set to
* @param {Object} options - The options to manipulate response before sending.
* @returns {ServerResponse} Array of all documents for the {@link CrudController#model} model
* or the empty Array if no documents have been found
*/
_aggregate: function (req, res, options) {
var self = this;
debugLogReq(req, this.logger);
let aggBody = req.body;
let promise = Promise.resolve();
try {
let flag = validateAggregation(aggBody);
if (!flag) promise = Promise.reject(new Error('Invalid key in aggregation body'));
}
catch (err) {
promise = Promise.reject(err);
}
return promise.then(() => this.model.aggregate(aggBody))
.then(documents => {
if (options && options.resHandler && typeof options.resHandler == 'function') {
let resVal = options.resHandler(undefined, res, documents, 200);
if (!res.headersSent) {
if (resVal instanceof Promise) {
return resVal.then(_docs => self.Okay(res, _docs))
} else {
return self.Okay(res, resVal)
}
}
return;
}
return self.Okay(res, documents);
})
.catch(err => {
if (options && options.resHandler && typeof options.resHandler == 'function') {
let resVal = options.resHandler(err, res);
if (!res.headersSent) {
if (resVal instanceof Promise) {
return resVal.then(_docs => self.Error(res, _docs ? docs : err))
} else {
return self.Error(res, resVal ? resVal : err)
}
}
return;
}
return self.Error(res, err);
});
},
/**
* Creates a new document in the DB.
* @param {IncomingMessage} req - The request message object containing the json document data
* @param {ServerResponse} res - The outgoing response object
* @returns {ServerResponse} The response status 201 CREATED or an error response
*/
_create: function (req, res) {
var self = this;
debugLogReq(req, this.logger);
var payload = 'data';
var reqParams = params.map(req);
var upsert = reqParams['upsert'];
var docIds = [];
var body = params.map(req)[payload];
var promise = Promise.resolve([]);
// if (upsert) {
// if (Array.isArray(body)) {
// docIds = body.map(doc => doc._id);
// docIds = docIds.filter(docs => docs);
// }
// else if (typeof body == "object") {
// docIds.push(body._id)
// }
// promise = self.model.find({ "_id": { "$in": docIds } });
// }
let newDocuments = [];
if (Array.isArray(body)) {
newDocuments = body;
} else {
newDocuments.push(body);
}
const results = [];
promise = newDocuments.reduce((prev, curr) => {
return prev.then(async () => {
let result, doc;
if (upsert && curr._id) {
doc = await self.model.findOne({ "_id": curr._id });
if (doc) {
_.mergeWith(doc, curr, self._customizer);
Object.keys(doc).forEach(el => doc.markModified(el));
}
}
if (!doc) {
doc = new self.model(curr);
}
try {
result = await doc.save(req);
results.push({ statusCode: 200, message: result });
return;
} catch (err) {
results.push({ statusCode: 400, message: { message: err.message } });
return;
}
});
}, Promise.resolve(null));
return promise.then(() => {
const documents = results;
var logObject = {
'operation': 'Create',
'user': req.user ? req.user.username : req.headers['masterName'],
'_id': documents.filter(_d => _d.statusCode === 200).map(_d => _d.message._id),
'timestamp': new Date()
};
self.logger.trace(JSON.stringify(logObject));
if (documents.some(_d => _d.statusCode === 400)) {
if (Array.isArray(body)) {
var result = documents.map(_doc => _doc.message);
// if (abortOnError && session) {
// handleSession(session, true);
// return res.status(400).json(result);
// } else
if ((documents.every(_d => _d.statusCode === 400))) {
return res.status(400).json(result);
} else {
return res.status(207).json(result);
}
} else {
return res.status(400).json(documents[0].message);
}
} else {
if (Array.isArray(body)) {
// if (abortOnError && session) handleSession(session, false);
return self.Okay(res, self.getResponseObject(documents.map(_d => _d.message)));
} else {
return self.Okay(res, self.getResponseObject(documents[0].message));
}
}
})
.catch(err => {
return self.Error(res, err);
});
},
_bulkShow: function (req, res) {
var sort = {};
debugLogReq(req, this.logger);
var reqParams = params.map(req);
var ids = reqParams['id'] ? reqParams['id'].split(',') : [];
reqParams['sort'] ? reqParams.sort.split(',').map(el => sort[el] = 1) : null;
var select = reqParams['select'] ? reqParams.select.split(',') : null;
var query = {
'_id': {
'$in': ids
},
'_metadata.deleted': false
};
var self = this;
var mq = this.model.find(query);
if (select) {
mq = mq.select(select.join(' '));
}
return mq.sort(sort).exec().then(result => self.Okay(res, result), err => this.Error(res, err));
},
_updateMapper: function (id, body, user, req) {
var self = this;
return new Promise((resolve, reject) => {
self.model.findOne({
'_id': id,
'_metadata.deleted': false
}, function (err, doc) {
if (err) {
resolve({ status: 400, data: { message: err.message } });
} else if (!doc) {
resolve({ status: 404, data: { message: 'Document not found' } });
} else {
var oldValues = doc.toObject();
var updated = _.mergeWith(doc, body, self._customizer);
if (_.isEqual(JSON.parse(JSON.stringify(oldValues)), JSON.parse(JSON.stringify(updated)))) {
resolve({ status: 200, data: updated });
return;
}
updated = new self.model(updated);
Object.keys(body).forEach(el => updated.markModified(el));
updated._oldDoc = JSON.parse(JSON.stringify(oldValues));
updated.save(req, function (err) {
if (err) {
return resolve({ status: 400, data: { message: err.message } });
}
var logObject = {
'operation': 'Update',
'user': user,
'originalValues': oldValues,
'_id': doc._id,
'newValues': body,
'timestamp': new Date()
};
self.logger.trace(JSON.stringify(logObject));
resolve({ status: 200, data: updated });
});
}
});
});
},
_bulkUpdate: function (req, res) {
var reqParams = params.map(req);
debugLogReq(req, this.logger);
var body = reqParams['data']; //Actual transformation
var selectFields = Object.keys(body);
var self = this;
selectFields.push('_id');
var ids = reqParams['id'] ? reqParams['id'].split(',') : []; //Ids will be comma seperated ID list
var user = req.user ? req.user.username : req.headers['masterName'];
var promises = ids.map(id => self._updateMapper(id, body, user, req));
var promise = Promise.all(promises).then(result => {
const resultData = result.map(e => e.data);
if (result && result.every(e => e.status == 200)) {
res.json(resultData);
} else if (result && result.every(e => e.status != 200)) {
res.status(400).json(resultData);
} else {
res.status(207).json(resultData);
}
// self.logger.debug("Sending Response:: " + JSON.stringify(result));
}, err => {
self.Error(res, err);
});
return promise;
},
_bulkUpload: function (req, res) {
try {
debugLogReq(req, this.logger);
let buffer = req.files.file[0].buffer.toString('utf8');
let rows = buffer.split('\n');
let keys = rows[0].split(',');
let products = [];
let self = this;
rows.splice(0, 1);
rows.forEach(el => {
let values = el.split(',');
values.length > 1 ? products.push(_.zipObject(keys, values)) : null;
});
return Promise.all(products.map(el => self._bulkPersist(el))).
then(result => {
res.status(200).json(result);
// self.logger.debug("Sending Response:: " + JSON.stringify(result));
});
} catch (e) {
res.status(400).json(e);
// self.logger.debug("Sending Response:: " + JSON.stringify(e));
}
},
_bulkPersist: function (el) {
var self = this;
return new Promise((res, rej) => {
self.model.create(el, function (err, doc) {
if (err)
res(err);
else
res(doc);
});
});
},
/**
* Updates an existing document in the DB. The requested document id is read from the
* request parameters by using the {@link CrudController#idName} property.
* @param {IncomingMessage} req - The request message object the id is read from
* @param {ServerResponse} res - The outgoing response object
* @params {String} in - The Body payload location, if not specified, the parameter is assumed to be 'body'
* @returns {ServerResponse} The updated document or NOT FOUND if no document has been found
*/
_update: function (req, res) {
var reqParams = params.map(req);
debugLogReq(req, this.logger);
var bodyIn = 'data';
var body = reqParams[bodyIn];
if (body._id) {
delete req.body._id;
}
var self = this;
var bodyData = _.omit(body, this.omit);
let oldValues = null;
let document = null;
let updated = null;
let resSentFlag = false;
return this.model.findOne({
'_id': reqParams['id'],
'_metadata.deleted': false
}).lean()
.then(_document => {
if (!_document) {
resSentFlag = true;
return self.NotFound(res);
}
oldValues = JSON.parse(JSON.stringify(_document));
document = _document;
updated = _.mergeWith(_document, bodyData, self._customizer);
if (_.isEqual(JSON.parse(JSON.stringify(updated)), JSON.parse(JSON.stringify(oldValues)))) return;
updated = new self.model(updated);
updated.isNew = false;
Object.keys(body).forEach(el => updated.markModified(el));
updated._oldDoc = JSON.parse(JSON.stringify(oldValues));
return updated.save(req);
})
.then(() => {
if (resSentFlag) return;
var logObject = {
'operation': 'Update',
'user': req.user ? req.user.username : req.headers['masterName'],
// 'originalValues': oldValues,
'_id': document._id,
// 'newValues': body,
'timestamp': new Date()
};
self.logger.trace(JSON.stringify(logObject));
return self.Okay(res, self.getResponseObject(updated));
})
.catch(err => {
self.Error(res, err);
})
},
_customizer: function (objValue, srcValue) {
if (_.isArray(objValue)) {
return srcValue;
}
},
/**
* Deletes a document from the DB. The requested document id is read from the
* request parameters by using the {@link CrudController#idName} property.
* @param {IncomingMessage} req - The request message object the id is read from
* @param {ServerResponse} res - The outgoing response object
* @returns {ServerResponse} A NO CONTENT response or NOT FOUND if no document has
* been found for the given id
*/
_destroy: function (req, res) {
var reqParams = params.map(req);
debugLogReq(req, this.logger);
var self = this;
let document = null;
return this.model.findOne({
'_id': reqParams['id']
})
.then(doc => {
if (!doc) {
return;
}
document = doc;
return doc.remove(req);
})
.then(() => {
var logObject = {
'operation': 'Destory',
'user': req.user ? req.user.username : req.headers['masterName'],
'_id': reqParams['id'],
'timestamp': new Date()
};
self.logger.trace(JSON.stringify(logObject));
return self.Okay(res, {});
})
.catch(err => {
return self.Error(res, err);
})
},
_bulkDestroy: function (req, res) {
let self = this;
bulkRemove(self, req, res, "destroy");
},
_markAsDeleted: function (req, res) {
var reqParams = params.map(req);
debugLogReq(req, this.logger);
var self = this;
let document = null;
return this.model.findOne({
'_id': reqParams['id'],
'_metadata.deleted': false
})
.then(doc => {
if (!doc) {
return;
}
doc._metadata.deleted = true;
document = JSON.parse(JSON.stringify(doc));
return doc.save(req);
})
.then(() => {
var logObject = {
'operation': 'Delete',
'user': req.user ? req.user.username : req.headers['masterName'],
'_id': document._id,
'timestamp': new Date()
};
self.logger.trace(JSON.stringify(logObject));
return self.Okay(res, {});
})
.catch(err => {
return self.Error(res, err);
});
},
_bulkMarkAsDeleted: function (req, res) {
let self = this;
bulkRemove(self, req, res, "markAsDeleted");
},
_rucc: function (queryObject, callBack) {
//rucc = Read Update Check Commit
var self = this;
debugLogReq(req, this.logger);
return this.model.findOne({
_id: queryObject['id'],
'_metadata.deleted': false
}).exec().then(result => {
if (result) {
var snapshot = result.toObject({
getters: false,
virtuals: false,
depopulate: true,
});
var newResult = callBack(result);
if (newResult && typeof newResult.then === 'function') {
//newResult is a promise, resolve it and then update.
return newResult.then(res => {
self.model.findOneAndUpdate(snapshot, res, {
upsert: false,
runValidators: true
});
})
.exec()
.then(updated => {
if (!updated) {
self.__rucc(queryObject, callBack); //Re-do the transaction.
} else {
return updated;
}
});
} else {
//newResult is a mongoose object
return self.model.findOneAndUpdate(snapshot, newResult, {
upsert: false,
runValidators: true
})
.exec()
.then(updated => {
if (!updated) {
self.___rucc(queryObject, callBack);
} else {
return updated;
}
});
}
} else {
return null;