-
Notifications
You must be signed in to change notification settings - Fork 242
/
model.js
999 lines (874 loc) · 27 KB
/
model.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
/**
* Module exports class Model
*/
module.exports = AbstractClass;
/**
* Module dependencies
*/
const setImmediate = global.setImmediate || process.nextTick;
const util = require('util');
const assert = require('assert');
const { ValidationError } = require('./validations.js');
require('./hooks.js');
require('./relations.js');
require('./include.js');
const BASE_TYPES = ['String', 'Boolean', 'Number', 'Date', 'Text'];
/**
* Model class - base class for all persist objects
* provides **common API** to access any database adapter.
* This class describes only abstract behavior layer, refer to `lib/adapters/*.js`
* to learn more about specific adapter implementations
*
* `AbstractClass` mixes `Validatable` and `Hookable` classes methods
*
* @constructor
* @param {Object} data - initial object data
*/
function AbstractClass(data) {
this._initProperties(data, true);
}
const promisedClassMethods = [
'create', 'all',
'destroyAll', 'upsert',
'updateOrCreate', 'findOrCreate',
'find', 'update', 'bulkUpdate',
'findOne', 'exists', 'count'
];
const promisedInstanceMethods = [
'save', 'updateAttribute', 'updateAttributes', 'destroy', 'reload'
];
AbstractClass.prototype._initProperties = function(data, applySetters) {
const self = this;
const ctor = this.constructor;
const ds = ctor.schema.definitions[ctor.modelName];
const properties = ds.properties;
data = data || {};
Object.defineProperty(this, '__cachedRelations', {
writable: true,
enumerable: false,
configurable: true,
value: {}
});
Object.defineProperty(this, '__data', {
writable: true,
enumerable: false,
configurable: true,
value: {}
});
Object.defineProperty(this, '__dataWas', {
writable: true,
enumerable: false,
configurable: true,
value: {}
});
if (data.__cachedRelations) {
this.__cachedRelations = data.__cachedRelations;
}
Object.keys(data).forEach(i => {
if (i in properties) {
this.__data[i] = this.__dataWas[i] = data[i];
} else if (i in ctor.relations) {
this.__data[ctor.relations[i].keyFrom] = this.__dataWas[i] = data[i][ctor.relations[i].keyTo];
this.__cachedRelations[i] = data[i];
}
});
if (applySetters === true) {
Object.keys(data).forEach(attr => {
self[attr] = data[attr];
});
}
ctor.forEachProperty(attr => {
if (typeof self.__data[attr] === 'undefined') {
self.__data[attr] = self.__dataWas[attr] = getDefault(attr);
} else {
self.__dataWas[attr] = self.__data[attr];
}
});
ctor.forEachProperty(attr => {
const type = properties[attr].type;
if (BASE_TYPES.indexOf(type.name) === -1) {
if (typeof self.__data[attr] !== 'object' && self.__data[attr]) {
try {
self.__data[attr] = JSON.parse(self.__data[attr] + '');
} catch (e) {
self.__data[attr] = String(self.__data[attr]);
}
}
if (type.name === 'Array' || typeof type === 'object' && type.constructor.name === 'Array') {
self.__data[attr] = JSON.parse(self.__data[attr] + '');
}
}
});
function getDefault(attr) {
const def = properties[attr]['default'];
if (isdef(def)) {
if (typeof def === 'function') {
return def();
}
return def;
}
return undefined;
}
this.trigger('initialize');
};
/**
* @param {String} prop - property name
* @param {Object} params - various property configuration
*/
AbstractClass.defineProperty = function(prop, params) {
this.schema.defineProperty(this.modelName, prop, params);
};
/**
* Updates the respective record
*
* @param {Object} params - { where:{uid:'10'}, update:{ Name:'New name' } }
* @param callback(err, obj)
*/
AbstractClass.update = function(id, data, cb) {
const Model = this;
if (typeof id === 'object' && arguments.length === 2 && typeof data === 'function') {
return util.deprecate(() => { Model.bulkUpdate(id, data); }, 'Model.update({update: ..., where: ...}): use Model.bulkUpdate instead')();
}
Model.bulkUpdate({ where: { id }, limit: 1, update: data }, cb);
};
/**
* Update records
*
* @param {Object} params - { where: { uid: '10'}, update: { Name: 'New name' }, limit: 1}
* - update {Object}: data to update
* - where {Object}: same as for Model.all, required
* - limit {Number}: same as for Model.all, optional
* - skip {Number}: same as for Model.all, optional
* @param callback(err, obj)
*/
AbstractClass.bulkUpdate = function(params, cb) {
const Model = this;
if (params instanceof Array) {
return Promise.all(params.map(param => {
return Model.bulkUpdate(param);
}))
.then(res => cb(null, res))
.catch(err => cb(err));
}
assert(params.update, 'Required update');
assert(params.where, 'Required where');
return this.schema.callAdapter('update', this.modelName, params, cb);
};
/**
* Create new instance of Model class, saved in database
*
* @param data [optional]
* @param callback(err, obj)
* callback called with arguments:
*
* - err (null or Error)
* - instance (null or Model)
*/
AbstractClass.create = function(data, callback) {
const Model = this;
const modelName = Model.modelName;
if (typeof data === 'function') {
callback = data;
data = {};
}
data = data || {};
// Passed via data from save
const options = data.options || { validate: true };
if (data.data instanceof Model) {
data = data.data;
data.__dataWas = data.__data;
}
let errors, gotError, instances, wait;
if (data instanceof Array) {
instances = Array(data.length);
errors = Array(data.length);
gotError = false;
wait = data.length;
if (wait === 0) {
callback(null, []);
}
for (let i = 0; i < data.length; i += 1) {
createModel(data[i], i);
}
return instances;
}
function createModel(d, i) {
Model.create(d, (err, inst) => {
if (err) {
errors[i] = err;
gotError = true;
}
instances[i] = inst;
modelCreated();
});
}
function modelCreated() {
wait += -1;
if (wait === 0) {
callback(gotError ? errors : null, instances);
}
}
let obj;
// if we come from save
if (data instanceof Model && !data.id) {
obj = data;
} else {
obj = new Model(data);
}
data = obj.toObject(true);
if (!options.validate) {
create();
} else {
// validation required
obj.isValid((err, valid) => {
if (valid) {
create();
} else {
err = err || new ValidationError(obj);
callback(err, obj);
}
}, data);
}
function create() {
obj.trigger('create', createDone => {
obj.trigger('save', function(saveDone) {
createAndTearDown(this, saveDone, createDone);
}, obj, callback);
}, obj, callback);
}
function createAndTearDown(inst, saveDone, createDone) {
inst.schema.callAdapter('create', modelName, obj.toObject(true), (err, id, rev) => {
if (id) {
obj.__data.id = id;
obj.__dataWas.id = id;
defineReadonlyProp(obj, 'id', id);
}
if (rev) {
obj._rev = rev;
}
// if error occurs, we should not return a valid obj
if (err) {
return callback(err, obj);
}
saveDone.call(obj, () => {
createDone.call(obj, () => {
callback(err, obj);
});
});
});
}
return obj;
};
function connection(schema) {
if (schema.connected) {
return Promise.resolve();
}
if (schema.connecting) {
return new Promise(resolve =>
schema.once('connected', () => resolve())
);
}
return schema.connect();
}
/**
* Update or insert
*/
AbstractClass.upsert = AbstractClass.updateOrCreate = function upsert(data, callback) {
const Model = this;
if (!data.id) {
return this.create(data, callback);
}
if (this.schema.adapter.updateOrCreate) {
const inst = new Model(data);
this.schema.callAdapter('updateOrCreate', Model.modelName, stripUndefined(inst.toObject(true)), (err, data) => {
if (data) {
return inst.reload(callback);
}
callback(err, null);
});
} else {
this.find(data.id, (err, inst) => {
if (err) {
return callback(err);
}
if (inst) {
inst.updateAttributes(data, callback);
} else {
const obj = new Model(data);
obj.save(data, callback);
}
});
}
function stripUndefined(data) {
return Object.keys(data)
.filter(key => typeof data[key] !== 'undefined')
.reduce((result, key) => {
result[key] = data[key];
return result;
}, {});
}
};
/**
* Find one record, same as `all`, limited by 1 and return object, not collection,
* if not found, create using data provided as second argument
*
* @param {Object} query - search conditions: {where: {test: 'me'}}.
* @param {Object} data - object to create.
* @param {Function} cb - callback called with (err, instance)
*/
AbstractClass.findOrCreate = function findOrCreate(query, data, callback) {
if (typeof data === 'function' || typeof data === 'undefined') {
callback = data;
data = query && query.where;
}
if (typeof query === 'function') {
callback = query;
query = { where: {} };
}
const t = this;
this.findOne(query)
.then(record => {
if (record) {
return callback(null, record);
}
t.create(data, callback);
})
.catch(callback);
};
/**
* Check whether object exists in database
*
* @param {id} id - identifier of object (primary key value)
* @param {Function} cb - callback called with (err, exists: Bool)
*/
AbstractClass.exists = function exists(id, cb) {
if (id) {
this.schema.callAdapter('exists', this.modelName, id, cb);
} else {
cb(new Error('Model::exists requires positive id argument'));
}
};
/**
* Find object by id
*
* @param {id} id - primary key value
* @param {Function} cb - callback called with (err, instance)
*/
AbstractClass.find = function find(id, cb) {
const Model = this;
this.schema.callAdapter('find', Model.modelName, id, (err, data) => {
let obj = null;
if (data) {
if (!data.id) {
data.id = id;
}
obj = new Model();
obj._initProperties(data, false);
}
cb(err, obj);
});
};
/**
* Find object by id, throw error with code not_found if not found
*
* @param {id} id - primary key value
* @param {Function} cb - callback called with (err, instance)
*/
AbstractClass.fetch = function fetch(id) {
return this.find(id)
.then(inst => {
if (inst) {
return inst;
}
const error = new Error('Not found');
error.code = 'not_found';
error.details = { id };
throw error;
});
};
AbstractClass.expand = function(object) {
return Object.assign({}, object, {
pets: [{}]
});
};
/**
* Find all instances of Model, matched by query
* make sure you have marked as `index: true` fields for filter or sort
*
* @param {Object} params (optional)
*
* - where: Object `{ key: val, key2: {gt: 'val2'}}`
* - attributes: Array ['id, 'name'] or String 'id'
* - include: String, Object or Array. See AbstractClass.include documentation.
* - order: String
* - limit: Number
* - skip: Number
*
* @param {Function} callback (required) called with arguments:
*
* - err (null or Error)
* - Array of instances
*/
AbstractClass.all = function all(params, cb) {
if (arguments.length === 1) {
cb = params;
params = null;
}
if (params) {
if ('skip' in params) {
params.offset = params.skip;
} else if ('offset' in params) {
params.skip = params.offset;
}
}
const Constr = this;
const paramsFiltered = params;
this.schema.callAdapter('all', this.modelName, paramsFiltered, (err, data) => {
if (data && data.forEach) {
if (params && params.attributes && data && data.length) {
if (typeof params.attributes === 'string') {
return cb(err, data.map(n => n[params.attributes]));
} else if (typeof data.map === 'function') {
const isClean = Object.getOwnPropertyNames(data[0]).every(key => {
return params.attributes.indexOf(key) !== -1;
});
if (!isClean) {
data.forEach(node => {
Object.keys(node).forEach(key => {
if (params.attributes.indexOf(key) === -1) {
delete node[key];
}
});
});
}
}
}
if (!params || !params.onlyKeys) {
data.forEach((d, i) => {
const obj = new Constr();
obj._initProperties(d, false);
if (params && params.include && params.collect) {
data[i] = obj.__cachedRelations[params.collect];
} else {
data[i] = obj;
}
});
}
if (data && data.countBeforeLimit) {
data.countBeforeLimit = data.countBeforeLimit;
}
cb(err, data);
} else {
cb(err, []);
}
});
};
/**
* Iterate through dataset and perform async method iterator. This method
* designed to work with large datasets loading data by batches.
*
* @param {Object} filter - query conditions. Same as for `all` may contain
* optional member `batchSize` to specify size of batch loaded from db. Optional.
* @param {Function} iterator - method(obj, next) called on each obj.
* @param {Function} callback - method(err) called on complete or error.
*/
AbstractClass.iterate = function map(filter, iterator, callback) {
const Model = this;
if (typeof filter === 'function') {
if (typeof iterator === 'function') {
callback = iterator;
}
iterator = filter;
filter = {};
}
const concurrent = filter.concurrent;
delete filter.concurrent;
let limit = filter.limit;
const batchSize = filter.limit = filter.batchSize || 1000;
let batchNumber = filter.batchNumber || -1;
nextBatch();
function nextBatch() {
// console.log(batchNumber);
batchNumber += 1;
filter.skip = filter.offset = batchNumber * batchSize;
if (limit < batchSize) {
if (limit <= 0) {
return done();
}
filter.limit = limit;
}
limit -= batchSize;
Model.all(filter).then(collection => {
if (collection.length === 0) {
return done();
}
let i = 0, wait;
if (concurrent) {
wait = collection.length;
collection.forEach((obj, i) => {
iterator(obj, next, filter.offset + i);
obj = null;
});
collection = null;
} else {
nextItem();
}
function next() {
wait += -1;
if (wait === 0) {
nextBatch();
}
}
function nextItem(err) {
if (err) {
return done(err);
}
const item = collection[i];
if (i > collection.length - 1) {
return nextBatch();
}
i += 1;
setImmediate(() => iterator(item, nextItem, filter.offset + i));
}
}).catch(done);
}
function done(err) {
if (typeof callback === 'function') {
callback(err);
}
}
};
/**
* Find one record, same as `all`, limited by 1 and return object, not collection
*
* @param {Object} params - search conditions: {where: {test: 'me'}}
* @param {Function} cb - callback called with (err, instance)
*/
AbstractClass.findOne = function findOne(params, cb) {
if (typeof params === 'function') {
cb = params;
params = {};
}
params.limit = 1;
this.all(params, (err, collection) => {
if (err || !collection || collection.length < 1) {
return cb(err, null);
}
cb(err, collection[0]);
});
};
/**
* Destroy all records
* @param {Function} cb - callback called with (err)
*/
AbstractClass.destroyAll = function destroyAll(cb) {
this.schema.callAdapter('destroyAll', this.modelName, err => cb(err));
};
/**
* Return count of matched records
*
* @param {Object} where - search conditions (optional)
* @param {Function} cb - callback, called with (err, count)
*/
AbstractClass.count = function(where, cb) {
if (typeof where === 'function') {
cb = where;
where = null;
}
this.schema.callAdapter('count', this.modelName, where, cb);
};
/**
* Return string representation of class
*
* @override default toString method
*/
AbstractClass.toString = function() {
return '[Model ' + this.modelName + ']';
};
/**
* Save instance. When instance haven't id, create method called instead.
* Triggers: validate, save, update | create
* @param options {validate: true, throws: false} [optional]
* @param callback(err, obj)
*/
AbstractClass.prototype.save = function(options, callback) {
if (typeof options == 'function') {
callback = options;
options = {};
}
options = options || {};
if (!('validate' in options)) {
options.validate = true;
}
if (!('throws' in options)) {
options.throws = false;
}
const inst = this;
let data = inst.toObject(true);
const Model = this.constructor;
const modelName = Model.modelName;
if (!this.id) {
// Pass options and this to create
data = {
data: this,
options
};
return Model.create(data, callback);
}
// validate first
if (!options.validate) {
return save();
}
inst.isValid((err, valid) => {
if (valid) {
return save();
}
err = err || new ValidationError(inst);
// throws option is dangerous for async usage
if (options.throws) {
throw err;
}
if (typeof callback === 'function') {
callback.call(inst, err);
}
}, data);
// then save
function save() {
inst.trigger('save', saveDone =>
inst.trigger('update', updateDone =>
updateAndTearDown(inst, updateDone, saveDone)
, data, callback)
, data, callback);
}
// TODO: revisit hooks model
function updateAndTearDown(inst, updateDone, saveDone) {
inst.schema.callAdapter('save', modelName, data, err => {
if (err) {
return callback && callback(err, inst);
}
inst._initProperties(data, false);
updateDone.call(inst, () => {
saveDone.call(inst, () => {
if (typeof callback === 'function') {
callback.call(inst, err, inst);
}
});
});
});
}
};
AbstractClass.prototype.isNewRecord = function() {
return !this.id;
};
/**
* Convert instance to Object
*
* @param {Boolean} onlySchema - restrict properties to schema only, default false
* when onlySchema == true, only properties defined in schema returned,
* otherwise all enumerable properties returned.
* @param {Boolean} cachedRelations - include cached relations to object, only
* taken into account when onlySchema is false.
* @returns {Object} - canonical object representation (no getters and setters).
*/
AbstractClass.prototype.toObject = function(onlySchema, cachedRelations) {
const data = {};
const self = this;
this.constructor.forEachProperty(attr => {
if (self.__data.hasOwnProperty(attr)) {
data[attr] = self[attr];
} else {
data[attr] = null;
}
});
if (!onlySchema) {
Object.keys(self).forEach(attr => {
if (!data.hasOwnProperty(attr)) {
data[attr] = self[attr];
}
});
if (cachedRelations === true && this.__cachedRelations) {
const relations = this.__cachedRelations;
Object.keys(relations).forEach(attr => {
if (!data.hasOwnProperty(attr)) {
data[attr] = relations[attr];
}
});
}
}
return data;
};
// AbstractClass.prototype.hasOwnProperty = function(prop) {
// return this.__data && this.__data.hasOwnProperty(prop) ||
// Object.getOwnPropertyNames(this).indexOf(prop) !== -1;
// };
AbstractClass.prototype.toJSON = function() {
return this.toObject(false, true);
};
/**
* Delete object from persistence
*
* @triggers `destroy` hook (async) before and after destroying object
*/
AbstractClass.prototype.destroy = function(cb) {
this.trigger('destroy', function(destroyed) {
this.schema.callAdapter('destroy', this.constructor.modelName, this.id, err => {
if (err) {
return cb(err);
}
destroyed(() => {
if (cb) {
cb();
}
});
});
}, this.toObject(), cb);
};
/**
* Update single attribute
*
* equals to `updateAttributes({name: value}, cb)
*
* @param {String} name - name of property
* @param {Mixed} value - value of property
* @param {Function} callback - callback called with (err, instance)
*/
AbstractClass.prototype.updateAttribute = function updateAttribute(name, value, callback) {
const data = {};
data[name] = value;
this.updateAttributes(data, callback);
};
/**
* Update set of attributes
*
* this method performs validation before updating
*
* @trigger `validation`, `save` and `update` hooks
* @param {Object} data - data to update
* @param {Function} callback - callback called with (err, instance)
*/
AbstractClass.prototype.updateAttributes = function updateAttributes(data, callback) {
const inst = this;
const modelName = this.constructor.modelName;
// update instance's properties
Object.keys(data).forEach(key => inst[key] = data[key]);
inst.isValid((err, valid) => {
if (!valid) {
err = err || new ValidationError(inst);
if (callback) {
callback.call(inst, err);
}
return;
}
inst.trigger('save', saveDone =>
inst.trigger('update', updateDone =>
saveAndTearDown(updateDone, saveDone)
, data, callback)
, data, callback);
}, data);
function saveAndTearDown(updateDone, saveDone) {
Object.keys(data).forEach(key => inst[key] = data[key]);
inst.schema.callAdapter('updateAttributes', modelName, inst.id, inst.toObject(true), err => {
if (!err) {
// update _was attrs
Object.keys(data).forEach(key => {
inst.__dataWas[key] = inst.__data[key];
});
}
updateDone.call(inst, () => {
saveDone.call(inst, () => {
if (callback) {
callback.call(inst, err, inst);
}
});
});
});
}
};
AbstractClass.prototype.fromObject = function(obj) {
Object.keys(obj).forEach(key => this[key] = obj[key]);
};
/**
* Checks is property changed based on current property and initial value
*
* @param {String} attr - property name
* @return Boolean
*/
AbstractClass.prototype.propertyChanged = function propertyChanged(attr) {
return this.__data[attr] !== this.__dataWas[attr];
};
/**
* Reload object from persistence
*
* @requires `id` member of `object` to be able to call `find`
* @param {Function} callback - called with (err, instance) arguments
*/
AbstractClass.prototype.reload = function reload(callback) {
this.constructor.find(this.id, callback);
};
AbstractClass.prototype.inspect = function() {
return util.inspect(this.__data, false, 4, true);
};
promisedClassMethods.forEach(methodName => {
AbstractClass[methodName] = wrapWithPromise(AbstractClass[methodName], true);
});
promisedInstanceMethods.forEach(methodName => {
AbstractClass.prototype[methodName] = wrapWithPromise(AbstractClass.prototype[methodName]);
});
function wrapWithPromise(fn, isClassMethod) {
return function promisedWrap() {
const args = [].slice.call(arguments);
const callback = typeof args[args.length - 1] === 'function'
? args.pop()
: null;
const self = this;
const Model = isClassMethod ? self : self.constructor;
let queryResult;
const promisedQuery = connection(Model.schema)
.then(() => {
return new Promise((resolve, reject) => {
args.push((err, result) => {
queryResult = result;
if (err) {
return reject(err);
}
resolve(result);
});
fn.apply(self, args);
});
});
if (callback) {
promisedQuery.then(result => callback(null, result), err => {
if (queryResult !== 'undefined') {
callback(err, queryResult);
} else {
callback(err);
}
});
} else {
return promisedQuery;
}
};
}
/**
* Check whether `s` is not undefined
* @param {Mixed} s
* @return {Boolean} s is undefined
*/
function isdef(s) {
return typeof s !== 'undefined';
}
/**
* Define readonly property on object
*
* @param {Object} obj
* @param {String} key
* @param {Mixed} value
*/
function defineReadonlyProp(obj, key, value) {
Object.defineProperty(obj, key, {
writable: false,
enumerable: true,
configurable: true,
value
});
}