-
Notifications
You must be signed in to change notification settings - Fork 80
/
Copy pathbase-document.js
597 lines (510 loc) · 19 KB
/
base-document.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
'use strict';
const _ = require('lodash');
const deprecate = require('depd')('camo');
const DB = require('./clients').getClient;
const isSupportedType = require('./validate').isSupportedType;
const isValidType = require('./validate').isValidType;
const isEmptyValue = require('./validate').isEmptyValue;
const isInChoices = require('./validate').isInChoices;
const isArray = require('./validate').isArray;
const isDocument = require('./validate').isDocument;
const isEmbeddedDocument = require('./validate').isEmbeddedDocument;
const isString = require('./validate').isString;
const isNumber = require('./validate').isNumber;
const isDate = require('./validate').isDate;
const ValidationError = require('./errors').ValidationError;
const normalizeType = function(property) {
// TODO: Only copy over stuff we support
let typeDeclaration = {};
if (property.type) {
typeDeclaration = property;
} else if (isSupportedType(property)) {
typeDeclaration.type = property;
} else {
throw new Error('Unsupported type or bad variable. ' +
'Remember, non-persisted objects must start with an underscore (_). Got:', property);
}
return typeDeclaration;
};
class BaseDocument {
constructor() {
this._schema = { // Defines document structure/properties
_id: { type: DB().nativeIdType() }, // Native ID to backend database
};
this._id = null;
}
// TODO: Is there a way to tell if a class is
// a subclass of something? Until I find out
// how, we'll be lazy use this.
static documentClass() {
throw new TypeError('You must override documentClass (static).');
}
documentClass() {
throw new TypeError('You must override documentClass.');
}
collectionName() {
// DEPRECATED
// Getting ready to remove this functionality
if (this._meta) {
return this._meta.collection;
}
return this.constructor.collectionName();
}
/**
* Get current collection name
*
* @returns {String}
*/
static collectionName() {
// DEPRECATED
// Getting ready to remove this functionality
let instance = new this();
if (instance._meta) {
return instance._meta.collection;
}
return this.name.toLowerCase() + 's';
}
get id() {
deprecate('Document.id - use Document._id instead');
return this._id;
}
set id(id) {
deprecate('Document.id - use Document._id instead');
this._id = id;
}
/**
* set schema
* @param {Object} extension
*/
schema(extension) {
const that = this;
if (!extension) return;
_.keys(extension).forEach(function(k) {
that[k] = extension[k];
});
}
/*
* Pre/post Hooks
*
* To add a hook, the extending class just needs
* to override the appropriate hook method below.
*/
preValidate() { }
postValidate() { }
preSave() { }
postSave() { }
preDelete() { }
postDelete() { }
/**
* Generate this._schema from fields
*
* TODO : EMBEDDED
* Need to share this with embedded
*/
generateSchema() {
const that = this;
_.keys(this).forEach(function(k) {
// Ignore private variables
if (_.startsWith(k, '_')) {
return;
}
// Normalize the type format
that._schema[k] = normalizeType(that[k]);
// Assign a default if needed
if (isArray(that._schema[k].type)) {
that[k] = that.getDefault(k) || [];
} else {
that[k] = that.getDefault(k);
}
});
}
/**
* Validate current document
*
* The method throw errors if document has invalid value
*
* TODO: This is not the right approach. The method needs to collect all
* errors in array and return them.
*/
validate() {
const that = this;
_.keys(that._schema).forEach(function(key) {
let value = that[key];
// TODO: This should probably be in Document, not BaseDocument
if (value !== null && value !== undefined) {
if (isEmbeddedDocument(value)) {
value.validate();
return;
} else if (isArray(value) && value.length > 0 && isEmbeddedDocument(value[0])) {
value.forEach(function(v) {
if (v.validate) {
v.validate();
}
});
return;
}
}
if (!isValidType(value, that._schema[key].type)) {
// TODO: Formatting should probably be done somewhere else
let typeName = null;
let valueName = null;
if (Array.isArray(that._schema[key].type) && that._schema[key].type.length > 0) {
typeName = '[' + that._schema[key].type[0].name + ']';
} else if (Array.isArray(that._schema[key].type) && that._schema[key].type.length === 0) {
typeName = '[]';
} else {
typeName = that._schema[key].type.name;
}
if (Array.isArray(value)) {
// TODO: Not descriptive enough! Strings can look like numbers
valueName = '[' + value.toString() + ']';
} else {
valueName = typeof(value);
}
throw new ValidationError('Value assigned to ' + that.collectionName() + '.' + key +
' should be ' + typeName + ', got ' + valueName);
}
if (that._schema[key].required && isEmptyValue(value)) {
throw new ValidationError('Key ' + that.collectionName() + '.' + key +
' is required' + ', but got ' + value);
}
if (that._schema[key].match && isString(value) && !that._schema[key].match.test(value)) {
throw new ValidationError('Value assigned to ' + that.collectionName() + '.' + key +
' does not match the regex/string ' + that._schema[key].match.toString() + '. Value was ' + value);
}
if (!isInChoices(that._schema[key].choices, value)) {
throw new ValidationError('Value assigned to ' + that.collectionName() + '.' + key +
' should be in choices [' + that._schema[key].choices.join(', ') + '], got ' + value);
}
if (isNumber(that._schema[key].min) && value < that._schema[key].min) {
throw new ValidationError('Value assigned to ' + that.collectionName() + '.' + key +
' is less than min, ' + that._schema[key].min + ', got ' + value);
}
if (isNumber(that._schema[key].max) && value > that._schema[key].max) {
throw new ValidationError('Value assigned to ' + that.collectionName() + '.' + key +
' is less than max, ' + that._schema[key].max + ', got ' + value);
}
if (typeof(that._schema[key].validate) === 'function' && !that._schema[key].validate(value)) {
throw new ValidationError('Value assigned to ' + that.collectionName() + '.' + key +
' failed custom validator. Value was ' + value);
}
});
}
/*
* Right now this only canonicalizes dates (integer timestamps
* get converted to Date objects), but maybe we should do the
* same for strings (UTF, Unicode, ASCII, etc)?
*/
canonicalize() {
const that = this;
_.keys(that._schema).forEach(function(key) {
let value = that[key];
if (that._schema[key].type === Date && isDate(value)) {
that[key] = new Date(value);
} else if (value !== null && value !== undefined &&
value.documentClass && value.documentClass() === 'embedded') {
// TODO: This should probably be in Document, not BaseDocument
value.canonicalize();
return;
}
});
}
/**
* Create new document from data
*
* @param {Object} data
* @returns {Document}
*/
static create(data) {
this.createIndexes();
if (typeof(data) !== 'undefined') {
return this._fromData(data);
}
return this._instantiate();
}
static createIndexes() { }
/**
* Create new document from self
*
* @returns {BaseDocument}
* @private
*/
static _instantiate() {
let instance = new this();
instance.generateSchema();
return instance;
}
// TODO: Should probably move some of this to
// Embedded and Document classes since Base shouldn't
// need to know about child classes
static _fromData(datas) {
const that = this;
if (!isArray(datas)) {
datas = [datas];
}
let documents = [];
let embeddedPromises = [];
datas.forEach(function(d) {
let instance = that._instantiate();
_.keys(d).forEach(function(key) {
let value = null;
if (d[key] === null) {
value = instance.getDefault(key);
} else {
value = d[key];
}
// If its not in the schema, we don't care about it... right?
if (key in instance._schema) {
let type = instance._schema[key].type;
if (type.documentClass && type.documentClass() === 'embedded') {
// Initialize EmbeddedDocument
instance[key] = type._fromData(value);
} else if (isArray(type) && type.length > 0 &&
type[0].documentClass && type[0].documentClass() === 'embedded') {
// Initialize array of EmbeddedDocuments
instance[key] = [];
value.forEach(function(v, i) {
instance[key][i] = type[0]._fromData(v);
});
} else {
// Initialize primitive or array of primitives
instance[key] = value;
}
} else if (key in instance) {
// Handles virtual setters
instance[key] = value;
}
});
documents.push(instance);
});
if (documents.length === 1) {
return documents[0];
}
return documents;
}
populate() {
return BaseDocument.populate(this);
}
/**
* Populates document references
*
* TODO : EMBEDDED
* @param {Array|Document} docs
* @param {Array} fields
* @returns {Promise}
*/
static populate(docs, fields) {
if (!docs) return Promise.all([]);
let documents = null;
if (!isArray(docs)) {
documents = [docs];
} else if (docs.length < 1) {
return Promise.all(docs);
} else {
documents = docs;
}
// Load all 1-level-deep references
// First, find all unique keys needed to be loaded...
let keys = [];
// TODO: Bad assumption: Not all documents in the database will have the same schema...
// Hmm, if this is true, thats an error on the user. Right?
let anInstance = documents[0];
_.keys(anInstance._schema).forEach(function(key) {
// Only populate specified fields
if (isArray(fields) && fields.indexOf(key) < 0) {
return;
}
// Handle array of references (ex: { type: [MyObject] })
if (isArray(anInstance._schema[key].type) &&
anInstance._schema[key].type.length > 0 &&
isDocument(anInstance._schema[key].type[0])) {
keys.push(key);
}
// Handle anInstance[key] being a string id, a native id, or a Document instance
else if ((isString(anInstance[key]) || DB().isNativeId(anInstance[key])) &&
isDocument(anInstance._schema[key].type)) {
keys.push(key);
}
});
// ...then get all ids for each type of reference to be loaded...
// ids = {
// houses: {
// 'abc123': ['ak23lj', '2kajlc', 'ckajl32'],
// 'l2jo99': ['28dsa0']
// },
// friends: {
// '1039da': ['lj0adf', 'k2jha']
// }
//}
let ids = {};
keys.forEach(function(k) {
ids[k] = {};
documents.forEach(function(d) {
ids[k][DB().toCanonicalId(d._id)] = [].concat(d[k]); // Handles values and arrays
// Also, initialize document member arrays
// to assign to later if needed
if (isArray(d[k])) {
d[k] = [];
}
});
});
// TODO: Is this really the most efficient
// way to do this? Maybe make a master list
// of all objects that need to be loaded (separated
// by type), load those, and then search through
// ids to see where dereferenced objects should
// go?
// ...then for each array of ids, load them all...
let loadPromises = [];
_.keys(ids).forEach(function(key) {
let keyIds = [];
_.keys(ids[key]).forEach(function(k) {
// Before adding to list, we convert id to the
// backend database's native ID format.
keyIds = keyIds.concat(ids[key][k]);
});
// Only want to load each reference once
keyIds = _.uniq(keyIds);
// Handle array of references (like [MyObject])
let type = null;
if (isArray(anInstance._schema[key].type)) {
type = anInstance._schema[key].type[0];
} else {
type = anInstance._schema[key].type;
}
// Bulk load dereferences
let p = type.find({ '_id': { $in: keyIds } }, { populate: false })
.then(function(dereferences) {
// Assign each dereferenced object to parent
_.keys(ids[key]).forEach(function(k) {
// TODO: Replace with documents.find when able
// Find the document to assign the derefs to
let doc;
documents.forEach(function(d) {
if (DB().toCanonicalId(d._id) === k) doc = d;
});
// For all ids to be dereferenced, find the
// deref and assign or push it
ids[key][k].forEach(function(id) {
// TODO: Replace with dereferences.find when able
// Find the right dereference
let deref;
dereferences.forEach(function(d) {
if (DB().toCanonicalId(d._id) === DB().toCanonicalId(id)) deref = d;
});
if (isArray(anInstance._schema[key].type)) {
doc[key].push(deref);
} else {
doc[key] = deref;
}
});
});
});
loadPromises.push(p);
});
// ...and finally execute all promises and return our
// fully loaded documents.
return Promise.all(loadPromises).then(function() {
return docs;
});
}
/**
* Get default value
*
* @param {String} schemaProp Key of current schema
* @returns {*}
*/
getDefault(schemaProp) {
if (schemaProp in this._schema && 'default' in this._schema[schemaProp]) {
let def = this._schema[schemaProp].default;
let defVal = typeof(def) === 'function' ? def() : def;
this[schemaProp] = defVal; // TODO: Wait... should we be assigning it here?
return defVal;
} else if (schemaProp === '_id') {
return null;
}
return undefined;
}
/**
* For JSON.Stringify
*
* @returns {*}
*/
toJSON() {
let values = this._toData({_id: true});
let schema = this._schema;
for (let key in schema) {
if (schema.hasOwnProperty(key)) {
if (schema[key].private){
delete values[key];
} else if (values[key] && values[key].toJSON) {
values[key] = values[key].toJSON();
} else if (isArray(values[key])) {
let newArray = [];
values[key].forEach(function(i) {
if (i && i.toJSON) {
newArray.push(i.toJSON());
} else {
newArray.push(i);
}
});
values[key] = newArray;
}
}
}
return values;
}
/**
*
* @param keep
* @returns {{}}
* @private
*/
_toData(keep) {
const that = this;
if (keep === undefined || keep === null) {
keep = {};
} else if (keep._id === undefined) {
keep._id = true;
}
let values = {};
_.keys(this).forEach(function(k) {
if (_.startsWith(k, '_')) {
if (k !== '_id' || !keep._id) {
return;
} else {
values[k] = that[k];
}
} else if (isEmbeddedDocument(that[k])) {
values[k] = that[k]._toData();
} else if (isArray(that[k]) && that[k].length > 0 && isEmbeddedDocument(that[k][0])) {
values[k] = [];
that[k].forEach(function(v) {
values[k].push(v._toData());
});
} else {
values[k] = that[k];
}
});
return values;
}
_getEmbeddeds() {
const that = this;
let embeddeds = [];
_.keys(this._schema).forEach(function(v) {
if (isEmbeddedDocument(that._schema[v].type) ||
(isArray(that._schema[v].type) && isEmbeddedDocument(that._schema[v].type[0]))) {
embeddeds = embeddeds.concat(that[v]);
}
});
return embeddeds;
}
_getHookPromises(hookName) {
let embeddeds = this._getEmbeddeds();
let hookPromises = [];
hookPromises = hookPromises.concat(_.invoke(embeddeds, hookName));
hookPromises.push(this[hookName]());
return hookPromises;
}
}
module.exports = BaseDocument;