/
schema.js
438 lines (374 loc) · 8.96 KB
/
schema.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
/**
* Module dependencies.
*/
var EventEmitter = require('events').EventEmitter
, Types = require('./schema/index')
, VirtualType = require('./virtualtype')
, utils = require('./utils')
, NamedScope = require('./namedscope')
, Query = require('./query');
/**
* Schema constructor.
*
* @param {Object} definition
* @api public
*/
function Schema (obj, options) {
this.paths = {};
this.virtuals = {};
this.inherits = {};
this.callQueue = [];
this._indexes = [];
this.methods = {};
this.statics = {};
this.tree = {};
// set options
this.options = utils.options({
safe: true
, 'use$SetOnSave': true
}, options);
// build paths
if (obj)
this.add(obj);
if (!this.paths['_id'])
this.add({ _id: {type: ObjectId, auto: true} });
if (!this.paths['id']) this.virtual('id').get(function () {
return this._id.toString();
});
};
/**
* Inherit from EventEmitter.
*/
Schema.prototype.__proto__ = EventEmitter.prototype;
/**
* Schema by paths
*
* Example (embedded doc):
* {
* 'test' : SchemaType,
* , 'test.test' : SchemaType,
* , 'first_name' : SchemaType
* }
*
* @api private
*/
Schema.prototype.paths;
/**
* Schema as a tree
*
* Example:
* {
* '_id' : ObjectId
* , 'nested' : {
* 'key': String
* }
* }
*
* @api private
*/
Schema.prototype.tree;
/**
* Sets the keys
*
* @param {Object} keys
* @param {String} prefix
* @api public
*/
Schema.prototype.add = function (obj, prefix) {
prefix = prefix || '';
for (var i in obj) {
// make sure set of keys are in `tree`
if (!prefix && !this.tree[i])
this.tree[i] = obj[i];
if (obj[i].constructor == Object && (!obj[i].type || obj[i].type.type)) {
if (Object.keys(obj[i]).length)
this.add(obj[i], prefix + i + '.');
else
this.path(prefix + i, obj[i]); // mixed type
} else
this.path(prefix + i, obj[i]);
}
};
/**
* Sets a path (if arity 2)
* Gets a path (if arity 1)
*
* @param {String} path
* @param {Object} constructor
* @api public
*/
Schema.prototype.path = function (path, obj) {
if (obj == undefined)
return this.paths[path];
if (obj.constructor != Object)
obj = { type: obj };
// Get the type making sure to allow keys named "type"
// and default to mixed if not specified.
// { type: { type: String, default: 'freshcut' } }
var type = obj.type && !obj.type.type
? obj.type
: {};
if (type.constructor == Object)
this.paths[path] = new Types.Mixed(path, obj);
else if (Array.isArray(type) || type == Array){
// if it was specified through { type } look for `cast`
var cast = type == Array
? obj.cast
: type[0];
cast = cast || Types.Mixed;
if (cast instanceof Schema)
this.paths[path] = new Types.DocumentArray(path, cast, obj);
else
this.paths[path] = new Types.Array(path, cast, obj);
} else
this.paths[path] = new Types[type.name](path, obj);
return this;
};
/**
* Iterates through the schema's paths, passing the path string and type object
* to the callback.
*
* @param {Function} callback function - fn(pathstring, type)
* @return {Schema} this for chaining
* @api public
*/
Schema.prototype.eachPath = function (fn) {
for (var k in this.paths)
if (this.paths.hasOwnProperty(k))
fn(k, this.paths[k]);
return this;
};
/**
* Returns an Array of path strings that are required.
* @api public
*/
Object.defineProperty(Schema.prototype, 'requiredPaths', {
get: function () {
var paths = this.paths
, pathnames = Object.keys(paths)
, i = pathnames.length
, pathname, path
, requiredPaths = [];
while (i--) {
pathname = pathnames[i];
path = paths[pathname];
if (path.isRequired) requiredPaths.push(pathname);
}
return requiredPaths;
}
});
/**
* Given a path, returns whether it is a real, virtual, or
* ad-hoc/undefined path
*
* @param {String} path
* @return {String}
* @api public
*/
Schema.prototype.pathType = function (path) {
if (path in this.paths) return 'real';
if (path in this.virtuals) return 'virtual';
return 'adhocOrUndefined';
};
/**
* Adds a method call to the queue
*
* @param {String} method name
* @param {Array} arguments
* @api private
*/
Schema.prototype.queue = function(name, args){
this.callQueue.push([name, args]);
return this;
};
/**
* Defines a pre for the document
*
* @param {String} method
* @param {Function} callback
* @api public
*/
Schema.prototype.pre = function(){
return this.queue('pre', arguments);
};
/**
* Defines a post for the document
*
* @param {String} method
* @param {Function} callback
* @api public
*/
Schema.prototype.post = function(method, fn){
return this.queue('on', arguments);
};
/**
* Registers a plugin for this schema
*
* @param {Function} plugin callback
* @api public
*/
Schema.prototype.plugin = function (fn, opts) {
fn(this, opts);
return this;
};
/**
* Adds a method
*
* @param {String} method name
* @param {Function} handler
* @api public
*/
Schema.prototype.method = function (name, fn) {
if ('string' != typeof name)
for (var i in name)
this.methods[i] = name[i];
else
this.methods[name] = fn;
return this;
};
/**
* Defines a static method
*
* @param {String} name
* @param {Function} handler
* @api public
*/
Schema.prototype.static = function(name, fn) {
if ('string' != typeof name)
for (var i in name)
this.statics[i] = name[i];
else
this.statics[name] = fn;
return this;
};
/**
* Defines an index (most likely compound)
* Example:
* schema.index({ first: 1, last: -1 })
*
* @param {Object} field
* @param {Object} optional options object
* @api public
*/
Schema.prototype.index = function (fields, options) {
this._indexes.push([fields, options || {}]);
return this;
};
/**
* Sets/gets an option
*
* @param {String} key
* @param {Object} optional value
* @api public
*/
Schema.prototype.set = function (key, value) {
if (arguments.length == 1)
return this.options[key];
this.options[key] = value;
return this;
};
/**
* Compiles indexes from fields and schema-level indexes
*
* @api public
*/
Schema.prototype.__defineGetter__('indexes', function () {
var index
, indexes = []
, seenSchemas = [];
function collectIndexes (paths, prefix) {
prefix = prefix || '';
for (var i in paths){
if (paths[i]) {
if (paths[i] instanceof Types.DocumentArray) {
// avoid recursion
if (!(~seenSchemas.indexOf(paths[i].schema))) {
seenSchemas.push(paths[i].schema);
collectIndexes(paths[i].schema.paths, i + '.');
}
} else {
index = paths[i]._index;
if (index !== false && index !== null){
var field = {};
field[prefix + i] = 1;
indexes.push([field, index.constructor == Object ? index : {} ]);
}
}
}
}
}
collectIndexes(this.paths);
return indexes.concat(this._indexes);
});
/**
* Retrieves or creates the virtual type with the given name.
*
* @param {String} name
* @return {VirtualType}
*/
Schema.prototype.virtual = function (name) {
var virtuals = this.virtuals || (this.virtuals = {});
var parts = name.split('.');
return virtuals[name] = parts.reduce( function (mem, part, i) {
mem[part] || (mem[part] = (i === parts.length-1)
? new VirtualType()
: {});
return mem[part];
}, this.tree);
};
/**
* Fetches the virtual type with the given name.
* Should be distinct from virtual because virtual auto-defines a new VirtualType
* if the path doesn't exist.
*
* @param {String} name
* @return {VirtualType}
*/
Schema.prototype.virtualpath = function (name) {
return this.virtuals[name];
};
Schema.prototype.namedScope = function (name, fn) {
var namedScopes = this.namedScopes || (this.namedScopes = new NamedScope)
, newScope = Object.create(namedScopes)
, allScopes = namedScopes.scopesByName || (namedScopes.scopesByName = {});
allScopes[name] = newScope;
newScope.name = name;
newScope.block = fn;
newScope.query = new Query();
newScope.decorate(namedScopes, {
block0: function (block) {
return function () {
block.call(this.query);
return this;
};
},
blockN: function (block) {
return function () {
block.apply(this.query, arguments);
return this;
};
},
basic: function (query) {
return function () {
this.query.find(query);
return this;
};
}
});
return newScope;
};
/**
* ObjectId schema identifier. Not an actual ObjectId, only used for Schemas.
*
* @api public
*/
function ObjectId () {
throw new Error('This is an abstract interface. Its only purpose is to mark '
+ 'fields as ObjectId in the schema creation.');
}
/**
* Module exports.
*/
module.exports = exports = Schema;
exports.Types = Types;
exports.ObjectId = ObjectId;