blackhole.db 2.0.2 → 3.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +191 -215
- package/lib/collection.js +299 -0
- package/lib/document.js +476 -0
- package/lib/engine.js +861 -0
- package/lib/errors.js +94 -0
- package/lib/objectid.js +50 -0
- package/lib/query.js +551 -0
- package/lib/schema.js +555 -0
- package/model.js +260 -0
- package/package.json +1 -1
package/lib/schema.js
ADDED
|
@@ -0,0 +1,555 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const ObjectId = require('./objectid');
|
|
3
|
+
const engine = require('./engine');
|
|
4
|
+
const { CastError, ValidatorError, ValidationError, StrictModeError } = require('./errors');
|
|
5
|
+
|
|
6
|
+
const { isObj, clone } = engine;
|
|
7
|
+
|
|
8
|
+
// Marker classes used as `type:` values (Schema.Types.X) and for instanceof checks.
|
|
9
|
+
class SchemaTypeMarker {}
|
|
10
|
+
const Types = {};
|
|
11
|
+
for (const name of ['String', 'Number', 'Boolean', 'Date', 'ObjectId', 'Buffer', 'Mixed', 'Array', 'Map', 'Decimal128', 'Embedded', 'DocumentArray', 'Subdocument', 'UUID', 'BigInt', 'Int32', 'Double']) {
|
|
12
|
+
Types[name] = { [name]: class extends SchemaTypeMarker {} }[name];
|
|
13
|
+
Object.defineProperty(Types[name], 'schemaName', { value: name });
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const KIND_OF_NAME = { String: 'String', Number: 'Number', Boolean: 'Boolean', Date: 'Date', ObjectId: 'ObjectId', Buffer: 'Buffer', Mixed: 'Mixed', Array: 'Array', Map: 'Map', Decimal128: 'Number', Int32: 'Number', Double: 'Number', BigInt: 'Number', UUID: 'String', Object: 'Mixed', Embedded: 'Mixed', Subdocument: 'Mixed', DocumentArray: 'Array' };
|
|
17
|
+
|
|
18
|
+
function kindOf(t) {
|
|
19
|
+
if (t === String) return 'String';
|
|
20
|
+
if (t === Number) return 'Number';
|
|
21
|
+
if (t === Boolean) return 'Boolean';
|
|
22
|
+
if (t === Date) return 'Date';
|
|
23
|
+
if (t === Buffer) return 'Buffer';
|
|
24
|
+
if (t === Object || t === Map && false) return 'Mixed';
|
|
25
|
+
if (t === Map) return 'Map';
|
|
26
|
+
if (t === Array) return 'Array';
|
|
27
|
+
if (t === ObjectId) return 'ObjectId';
|
|
28
|
+
if (t === Types.Mixed) return 'Mixed';
|
|
29
|
+
if (typeof t === 'function' && t.schemaName) return KIND_OF_NAME[t.schemaName];
|
|
30
|
+
if (typeof t === 'string') return KIND_OF_NAME[t] || KIND_OF_NAME[t[0].toUpperCase() + t.slice(1)];
|
|
31
|
+
if (typeof t === 'function' && t.name && KIND_OF_NAME[t.name]) return KIND_OF_NAME[t.name];
|
|
32
|
+
return undefined;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const OPTION_KEYS = new Set(['type', 'required', 'default', 'enum', 'min', 'max', 'minlength', 'maxlength', 'minLength', 'maxLength', 'match', 'trim', 'lowercase', 'uppercase', 'validate', 'get', 'set', 'unique', 'index', 'sparse', 'immutable', 'select', 'ref', 'alias', 'of', 'text', 'expires', 'transform', 'cast', 'refPath', 'populate', 'autopopulate', 'ref']);
|
|
36
|
+
|
|
37
|
+
class Schema {
|
|
38
|
+
constructor(definition, options = {}) {
|
|
39
|
+
this.obj = definition;
|
|
40
|
+
this.options = { strict: true, minimize: true, versionKey: '__v', id: true, _id: true, ...options };
|
|
41
|
+
this.paths = {};
|
|
42
|
+
this.nested = {};
|
|
43
|
+
this.virtuals = {};
|
|
44
|
+
this.methods = {};
|
|
45
|
+
this.statics = {};
|
|
46
|
+
this.query = {};
|
|
47
|
+
this.subpaths = {};
|
|
48
|
+
this.childSchemas = [];
|
|
49
|
+
this.tree = {};
|
|
50
|
+
this._hooks = { pre: [], post: [] };
|
|
51
|
+
this._indexes = [];
|
|
52
|
+
this._tree = new Map();
|
|
53
|
+
this.plugins = [];
|
|
54
|
+
if (definition) this.add(definition);
|
|
55
|
+
if (this.options.versionKey && !this.paths[this.options.versionKey]) this.paths[this.options.versionKey] = makeNode(this.options.versionKey, {}, 'Number');
|
|
56
|
+
if (this.options._id !== false && !this.paths._id) this.paths._id = makeNode('_id', { auto: true }, 'ObjectId');
|
|
57
|
+
else if (this.options._id === false) delete this.paths._id;
|
|
58
|
+
if (this.options.timestamps) {
|
|
59
|
+
const t = this.options.timestamps === true ? {} : this.options.timestamps;
|
|
60
|
+
this.options.timestamps = { createdAt: t.createdAt === undefined ? 'createdAt' : t.createdAt, updatedAt: t.updatedAt === undefined ? 'updatedAt' : t.updatedAt };
|
|
61
|
+
const { createdAt, updatedAt } = this.options.timestamps;
|
|
62
|
+
if (createdAt && !this.paths[createdAt]) this.paths[createdAt] = makeNode(createdAt, { immutable: true }, 'Date');
|
|
63
|
+
if (updatedAt && !this.paths[updatedAt]) this.paths[updatedAt] = makeNode(updatedAt, {}, 'Date');
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
add(obj, prefix = '') {
|
|
68
|
+
if (obj instanceof Schema) { for (const [k, v] of Object.entries(obj.paths)) if (k !== '_id') this.paths[prefix + k] = v; return this; }
|
|
69
|
+
for (const key of Object.keys(obj)) {
|
|
70
|
+
const path = prefix + key;
|
|
71
|
+
const def = obj[key];
|
|
72
|
+
this.interpret(path, def);
|
|
73
|
+
}
|
|
74
|
+
return this;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
interpret(path, def) {
|
|
78
|
+
if (def === undefined || def === null) throw new TypeError(`Invalid value for schema path \`${path}\`, got value "${def}"`);
|
|
79
|
+
if (def instanceof Schema) { this.paths[path] = makeNode(path, {}, 'Embedded', { schema: def }); this.childSchemas.push({ schema: def, path }); return; }
|
|
80
|
+
if (Array.isArray(def)) { this.paths[path] = arrayNode(this, path, {}, def.length ? def[0] : undefined, def.length === 0); return; }
|
|
81
|
+
if (typeof def === 'function' || typeof def === 'string') {
|
|
82
|
+
const kind = kindOf(def);
|
|
83
|
+
if (!kind) throw new TypeError(`Invalid schema configuration: \`${path}\` is not a valid type at path \`${path}\`.`);
|
|
84
|
+
this.paths[path] = kind === 'Array' ? arrayNode(this, path, {}, undefined, true) : makeNode(path, {}, kind);
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
if (isObj(def)) {
|
|
88
|
+
const hasType = 'type' in def && !(isObj(def.type) && 'type' in def.type && !(def.type instanceof Schema));
|
|
89
|
+
if (!hasType) {
|
|
90
|
+
if (Object.keys(def).length === 0) { this.paths[path] = makeNode(path, {}, 'Mixed'); return; }
|
|
91
|
+
this.nested[path] = true;
|
|
92
|
+
for (const k of Object.keys(def)) this.interpret(`${path}.${k}`, def[k]);
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
const opts = { ...def };
|
|
96
|
+
const t = def.type;
|
|
97
|
+
if (t instanceof Schema) { this.paths[path] = makeNode(path, opts, 'Embedded', { schema: t }); this.childSchemas.push({ schema: t, path }); }
|
|
98
|
+
else if (Array.isArray(t)) this.paths[path] = arrayNode(this, path, opts, t.length ? t[0] : undefined, t.length === 0);
|
|
99
|
+
else if (isObj(t)) {
|
|
100
|
+
if (Object.keys(t).length === 0) this.paths[path] = makeNode(path, opts, 'Mixed');
|
|
101
|
+
else { const sub = new Schema(t); this.paths[path] = makeNode(path, opts, 'Embedded', { schema: sub }); this.childSchemas.push({ schema: sub, path }); }
|
|
102
|
+
} else {
|
|
103
|
+
const kind = kindOf(t);
|
|
104
|
+
if (!kind) throw new TypeError(`Invalid schema configuration: \`${typeof t === 'function' ? t.name : t}\` is not a valid type at path \`${path}\`.`);
|
|
105
|
+
if (kind === 'Array') this.paths[path] = arrayNode(this, path, opts, def.of, !def.of);
|
|
106
|
+
else if (kind === 'Map') this.paths[path] = makeNode(path, opts, 'Map', { of: def.of === undefined ? makeNode(`${path}.$*`, {}, 'Mixed') : this.elementNode(`${path}.$*`, def.of) });
|
|
107
|
+
else this.paths[path] = makeNode(path, opts, kind);
|
|
108
|
+
}
|
|
109
|
+
const node = this.paths[path];
|
|
110
|
+
if (opts.unique || opts.index || opts.sparse || opts.expires || opts.text) {
|
|
111
|
+
const indexOpts = {};
|
|
112
|
+
if (opts.unique) indexOpts.unique = true;
|
|
113
|
+
if (opts.sparse) indexOpts.sparse = true;
|
|
114
|
+
if (opts.expires) indexOpts.expireAfterSeconds = typeof opts.expires === 'number' ? opts.expires : 0;
|
|
115
|
+
this._indexes.push([{ [path]: opts.index && typeof opts.index === 'string' ? opts.index : opts.text ? 'text' : 1 }, indexOpts]);
|
|
116
|
+
}
|
|
117
|
+
return node;
|
|
118
|
+
}
|
|
119
|
+
throw new TypeError(`Invalid schema configuration for \`${path}\``);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
elementNode(path, def) {
|
|
123
|
+
const holder = new Schema({ [path.split('.').pop()]: def }, { _id: false });
|
|
124
|
+
const node = holder.paths[path.split('.').pop()];
|
|
125
|
+
node.path = path;
|
|
126
|
+
return node;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
path(p, def) {
|
|
130
|
+
if (def !== undefined) { this.interpret(p, def); return this.paths[p]; }
|
|
131
|
+
if (this.paths[p]) return this.paths[p];
|
|
132
|
+
// array element path ("tags.$") and subdocument paths ("items.0.name")
|
|
133
|
+
const parts = p.split('.');
|
|
134
|
+
for (let i = parts.length - 1; i > 0; i--) {
|
|
135
|
+
const head = this.paths[parts.slice(0, i).join('.')];
|
|
136
|
+
const rest = parts.slice(i);
|
|
137
|
+
if (head && (head.kind === 'Array' || head.kind === 'Embedded')) {
|
|
138
|
+
const sub = head.kind === 'Array' ? head.of : head;
|
|
139
|
+
const clean = rest.filter((x, idx) => !(/^\d+$/.test(x) || x === '$') || idx === rest.length - 1 && false);
|
|
140
|
+
if (head.kind === 'Array' && clean.length === 0) return head.of;
|
|
141
|
+
if (sub && sub.schema && clean.length) return sub.schema.path(clean.join('.'));
|
|
142
|
+
}
|
|
143
|
+
if (head && head.kind === 'Map') return head.of;
|
|
144
|
+
}
|
|
145
|
+
return undefined;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
pathType(p) {
|
|
149
|
+
if (this.paths[p]) return 'real';
|
|
150
|
+
if (this.virtuals[p]) return 'virtual';
|
|
151
|
+
if (this.nested[p]) return 'nested';
|
|
152
|
+
if (this.path(p)) return 'real';
|
|
153
|
+
return 'adhocOrUndefined';
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
eachPath(fn) { for (const [p, n] of Object.entries(this.paths)) fn(p, n); return this; }
|
|
157
|
+
requiredPaths() { return Object.keys(this.paths).filter((p) => this.paths[p].opts.required); }
|
|
158
|
+
|
|
159
|
+
pre(name, opts, fn) { if (typeof opts === 'function') { fn = opts; opts = {}; } this._hooks.pre.push({ name, fn, opts: opts || {} }); return this; }
|
|
160
|
+
post(name, opts, fn) { if (typeof opts === 'function') { fn = opts; opts = {}; } this._hooks.post.push({ name, fn, opts: opts || {} }); return this; }
|
|
161
|
+
hooksFor(kind, event) {
|
|
162
|
+
return this._hooks[kind].filter((h) => (Array.isArray(h.name) ? h.name.some((n) => hookMatch(n, event)) : hookMatch(h.name, event)));
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
virtual(name, options) {
|
|
166
|
+
const v = new VirtualType(name, options);
|
|
167
|
+
this.virtuals[name] = v;
|
|
168
|
+
return v;
|
|
169
|
+
}
|
|
170
|
+
virtualpath(name) { return this.virtuals[name]; }
|
|
171
|
+
plugin(fn, opts) { fn(this, opts); this.plugins.push({ fn, opts }); return this; }
|
|
172
|
+
index(fields, opts = {}) { this._indexes.push([fields, opts]); return this; }
|
|
173
|
+
indexes() { return this._indexes.map(([f, o]) => [f, { ...o }]); }
|
|
174
|
+
set(key, value) { if (arguments.length === 1) return this.options[key]; this.options[key] = value; return this; }
|
|
175
|
+
get(key) { return this.options[key]; }
|
|
176
|
+
loadClass(cls) {
|
|
177
|
+
for (const name of Object.getOwnPropertyNames(cls.prototype)) {
|
|
178
|
+
if (name === 'constructor') continue;
|
|
179
|
+
const d = Object.getOwnPropertyDescriptor(cls.prototype, name);
|
|
180
|
+
if (d.get || d.set) { const v = this.virtual(name); if (d.get) v.get(d.get); if (d.set) v.set(d.set); } else if (typeof d.value === 'function') this.methods[name] = d.value;
|
|
181
|
+
}
|
|
182
|
+
for (const name of Object.getOwnPropertyNames(cls)) if (typeof cls[name] === 'function' && !['length', 'name', 'prototype'].includes(name)) this.statics[name] = cls[name];
|
|
183
|
+
return this;
|
|
184
|
+
}
|
|
185
|
+
clone() {
|
|
186
|
+
const s = new Schema(this.obj, { ...this.options });
|
|
187
|
+
Object.assign(s.methods, this.methods); Object.assign(s.statics, this.statics); Object.assign(s.query, this.query);
|
|
188
|
+
s.virtuals = { ...this.virtuals }; s._hooks = { pre: [...this._hooks.pre], post: [...this._hooks.post] }; s._indexes = [...this._indexes];
|
|
189
|
+
return s;
|
|
190
|
+
}
|
|
191
|
+
remove(paths) { for (const p of [].concat(paths)) { delete this.paths[p]; delete this.nested[p]; } return this; }
|
|
192
|
+
pick() { return this; }
|
|
193
|
+
}
|
|
194
|
+
Schema.Types = Types;
|
|
195
|
+
Schema.ObjectId = Types.ObjectId;
|
|
196
|
+
Schema.reserved = Object.create(null);
|
|
197
|
+
|
|
198
|
+
function hookMatch(pattern, event) { return pattern instanceof RegExp ? pattern.test(event) : pattern === event; }
|
|
199
|
+
|
|
200
|
+
class VirtualType {
|
|
201
|
+
constructor(name, options = {}) { this.path = name; this.options = options; this.getters = []; this.setters = []; }
|
|
202
|
+
get(fn) { this.getters.push(fn); return this; }
|
|
203
|
+
set(fn) { this.setters.push(fn); return this; }
|
|
204
|
+
applyGetters(value, doc) { let v = value; for (const g of this.getters) v = g.call(doc, v, this, doc); return v; }
|
|
205
|
+
applySetters(value, doc) { let v = value; for (const s of this.setters) v = s.call(doc, v, this, doc); return v; }
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function makeNode(path, opts, kind, extra) {
|
|
209
|
+
const node = { path, opts: opts || {}, kind, instance: kind === 'Embedded' ? 'Embedded' : kind, ...extra };
|
|
210
|
+
node.options = node.opts;
|
|
211
|
+
node.isRequired = !!node.opts.required;
|
|
212
|
+
node.enumValues = Array.isArray(node.opts.enum) ? node.opts.enum : node.opts.enum && node.opts.enum.values ? node.opts.enum.values : [];
|
|
213
|
+
node.defaultValue = node.opts.default;
|
|
214
|
+
node.schema = extra && extra.schema;
|
|
215
|
+
node.validators = [];
|
|
216
|
+
return node;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function arrayNode(schema, path, opts, elementDef, mixed) {
|
|
220
|
+
let of;
|
|
221
|
+
if (mixed || elementDef === undefined) of = makeNode(`${path}.$`, {}, 'Mixed');
|
|
222
|
+
else if (elementDef instanceof Schema) { of = makeNode(`${path}.$`, {}, 'Embedded', { schema: elementDef }); schema.childSchemas.push({ schema: elementDef, path }); }
|
|
223
|
+
else if (isObj(elementDef) && !('type' in elementDef && !(isObj(elementDef.type) && 'type' in elementDef.type))) {
|
|
224
|
+
if (Object.keys(elementDef).length === 0) of = makeNode(`${path}.$`, {}, 'Mixed');
|
|
225
|
+
else { const sub = new Schema(elementDef); of = makeNode(`${path}.$`, {}, 'Embedded', { schema: sub }); schema.childSchemas.push({ schema: sub, path }); }
|
|
226
|
+
} else of = schema.elementNode(`${path}.$`, elementDef);
|
|
227
|
+
const node = makeNode(path, opts, 'Array', { of });
|
|
228
|
+
node.caster = of;
|
|
229
|
+
node.casterConstructor = of;
|
|
230
|
+
node.schema = of.schema;
|
|
231
|
+
return node;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// ---------- casting ----------
|
|
235
|
+
const TRUE = new Set([true, 'true', 1, '1', 'yes']);
|
|
236
|
+
const FALSE = new Set([false, 'false', 0, '0', 'no']);
|
|
237
|
+
|
|
238
|
+
function describe(node) { return node.kind === 'Array' ? `[${node.of.kind === 'Embedded' ? 'Embedded' : node.of.kind}]`.replace('[Mixed]', 'Array') : node.kind === 'Embedded' ? 'Embedded' : node.kind; }
|
|
239
|
+
|
|
240
|
+
function castLeaf(node, v, path) {
|
|
241
|
+
switch (node.kind) {
|
|
242
|
+
case 'String':
|
|
243
|
+
if (typeof v === 'string') return v;
|
|
244
|
+
if (typeof v === 'number' || typeof v === 'boolean' || typeof v === 'bigint') return String(v);
|
|
245
|
+
if (v instanceof Date) return v.toString();
|
|
246
|
+
if (v && typeof v === 'object' && !Array.isArray(v) && typeof v.toString === 'function' && v.toString !== Object.prototype.toString) return v.toString();
|
|
247
|
+
throw new CastError('string', v, path);
|
|
248
|
+
case 'Number': {
|
|
249
|
+
if (typeof v === 'number') { if (Number.isNaN(v)) throw new CastError('Number', v, path); return v; }
|
|
250
|
+
if (v === '') return null;
|
|
251
|
+
if (typeof v === 'boolean') return v ? 1 : 0;
|
|
252
|
+
if (v instanceof Date) return v.getTime();
|
|
253
|
+
if (typeof v === 'string' || typeof v === 'bigint') { const n = Number(v); if (Number.isNaN(n)) throw new CastError('Number', v, path); return n; }
|
|
254
|
+
if (v && typeof v.valueOf === 'function' && typeof v.valueOf() === 'number') return v.valueOf();
|
|
255
|
+
throw new CastError('Number', v, path);
|
|
256
|
+
}
|
|
257
|
+
case 'Boolean':
|
|
258
|
+
if (typeof v === 'boolean') return v;
|
|
259
|
+
if (TRUE.has(v)) return true;
|
|
260
|
+
if (FALSE.has(v)) return false;
|
|
261
|
+
throw new CastError('boolean', v, path);
|
|
262
|
+
case 'Date': {
|
|
263
|
+
if (v instanceof Date) { if (Number.isNaN(v.getTime())) throw new CastError('date', v, path); return v; }
|
|
264
|
+
if (v === '') return null;
|
|
265
|
+
let d;
|
|
266
|
+
if (typeof v === 'number') d = new Date(v);
|
|
267
|
+
else if (typeof v === 'string') d = /^-?\d+$/.test(v) ? new Date(Number(v)) : new Date(v);
|
|
268
|
+
else throw new CastError('date', v, path);
|
|
269
|
+
if (Number.isNaN(d.getTime())) throw new CastError('date', v, path);
|
|
270
|
+
return d;
|
|
271
|
+
}
|
|
272
|
+
case 'ObjectId':
|
|
273
|
+
if (v instanceof ObjectId) return v;
|
|
274
|
+
if (typeof v === 'string' || typeof v === 'number') { if (!ObjectId.isValid(v)) throw new CastError('ObjectId', v, path); return new ObjectId(v); }
|
|
275
|
+
if (v && typeof v === 'object' && v._id !== undefined && v._id !== v) return castLeaf(node, v._id, path);
|
|
276
|
+
if (v && typeof v.toHexString === 'function') return new ObjectId(v.toHexString());
|
|
277
|
+
throw new CastError('ObjectId', v, path);
|
|
278
|
+
case 'Buffer':
|
|
279
|
+
if (Buffer.isBuffer(v)) return v;
|
|
280
|
+
if (typeof v === 'string' || Array.isArray(v)) return Buffer.from(v);
|
|
281
|
+
if (v && v.type === 'Buffer' && Array.isArray(v.data)) return Buffer.from(v.data);
|
|
282
|
+
if (v && v.buffer) return Buffer.from(v.buffer);
|
|
283
|
+
throw new CastError('Buffer', v, path);
|
|
284
|
+
default: return v;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// Cast a value for one schema node. `strict` controls unknown keys in subdocuments.
|
|
289
|
+
function castValue(node, v, path, opts = {}) {
|
|
290
|
+
if (v === null || v === undefined) return v;
|
|
291
|
+
switch (node.kind) {
|
|
292
|
+
case 'Mixed': return v;
|
|
293
|
+
case 'Array': {
|
|
294
|
+
const items = Array.isArray(v) ? v : (v && typeof v.toObject === 'function' && Array.isArray(v.toObject())) ? v.toObject() : [v];
|
|
295
|
+
if (node.of.kind === 'Mixed') return items;
|
|
296
|
+
const out = new Array(items.length);
|
|
297
|
+
try {
|
|
298
|
+
for (let i = 0; i < items.length; i++) out[i] = castValue(node.of, items[i], `${path}.${i}`, opts);
|
|
299
|
+
} catch (e) {
|
|
300
|
+
if (e instanceof CastError && !(e.kind || '').startsWith('[')) throw new CastError(describe(node).replace(/^\[/, '[').toLowerCase().replace('embedded', 'Embedded'), v, path, e);
|
|
301
|
+
throw e;
|
|
302
|
+
}
|
|
303
|
+
return out;
|
|
304
|
+
}
|
|
305
|
+
case 'Map': {
|
|
306
|
+
const entries = v instanceof Map ? [...v.entries()] : Object.entries(v);
|
|
307
|
+
const m = new Map();
|
|
308
|
+
for (const [k, x] of entries) m.set(k, castValue(node.of, x, `${path}.${k}`, opts));
|
|
309
|
+
return m;
|
|
310
|
+
}
|
|
311
|
+
case 'Embedded': {
|
|
312
|
+
const src = v && v.$isblackholeDocument ? v.toObject() : v;
|
|
313
|
+
if (!isObj(src)) throw new CastError('Embedded', v, path);
|
|
314
|
+
const sub = castDocument(node.schema, src, path, opts);
|
|
315
|
+
applyDefaults(node.schema, sub, sub);
|
|
316
|
+
ensureSubId(node.schema, sub);
|
|
317
|
+
return sub;
|
|
318
|
+
}
|
|
319
|
+
default: return castLeaf(node, v, path);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function applyStringOptions(node, v) {
|
|
324
|
+
if (typeof v !== 'string') return v;
|
|
325
|
+
if (node.opts.trim) v = v.trim();
|
|
326
|
+
if (node.opts.lowercase) v = v.toLowerCase();
|
|
327
|
+
if (node.opts.uppercase) v = v.toUpperCase();
|
|
328
|
+
return v;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// Full pipeline for assigning a value to a path: setters, cast, string options.
|
|
332
|
+
function applySetters(node, v, path, scope) {
|
|
333
|
+
const setter = node.opts.set;
|
|
334
|
+
if (typeof setter === 'function') v = setter.call(scope, v, node);
|
|
335
|
+
if (v === null || v === undefined) return v;
|
|
336
|
+
v = castValue(node, v, path);
|
|
337
|
+
return node.kind === 'String' ? applyStringOptions(node, v) : v;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// Cast a plain object against a schema (used for new documents, subdocuments and $set of whole objects).
|
|
341
|
+
function castDocument(schema, src, prefix = '', opts = {}) {
|
|
342
|
+
const out = {};
|
|
343
|
+
const strict = opts.strict === undefined ? schema.options.strict : opts.strict;
|
|
344
|
+
const fullPrefix = prefix;
|
|
345
|
+
for (const key of Object.keys(src)) {
|
|
346
|
+
const value = src[key];
|
|
347
|
+
const path = key;
|
|
348
|
+
const node = schema.paths[path];
|
|
349
|
+
if (node) {
|
|
350
|
+
const cast = value === undefined ? undefined : applySetters(node, value, fullPrefix ? `${fullPrefix}.${path}` : path, src);
|
|
351
|
+
if (cast !== undefined) out[key] = cast;
|
|
352
|
+
} else if (schema.nested[path]) {
|
|
353
|
+
if (isObj(value)) out[key] = castNested(schema, path, value, fullPrefix, opts);
|
|
354
|
+
} else if (key === '__v' || key === schema.options.versionKey) {
|
|
355
|
+
out[key] = value;
|
|
356
|
+
} else if (schema.virtuals[key]) {
|
|
357
|
+
// virtual setters are applied by the document layer
|
|
358
|
+
} else if (strict === 'throw') throw new StrictModeError(key);
|
|
359
|
+
else if (strict === false) out[key] = value;
|
|
360
|
+
}
|
|
361
|
+
return out;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
function castNested(schema, nestedPath, value, prefix, opts) {
|
|
365
|
+
const out = {};
|
|
366
|
+
for (const key of Object.keys(value)) {
|
|
367
|
+
const path = `${nestedPath}.${key}`;
|
|
368
|
+
const node = schema.paths[path];
|
|
369
|
+
const label = prefix ? `${prefix}.${path}` : path;
|
|
370
|
+
if (node) { const c = value[key] === undefined ? undefined : applySetters(node, value[key], label, value); if (c !== undefined) out[key] = c; }
|
|
371
|
+
else if (schema.nested[path]) { if (isObj(value[key])) out[key] = castNested(schema, path, value[key], prefix, opts); }
|
|
372
|
+
else if (schema.options.strict === 'throw') throw new StrictModeError(path);
|
|
373
|
+
else if (schema.options.strict === false) out[key] = value[key];
|
|
374
|
+
}
|
|
375
|
+
return out;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
// ---------- defaults ----------
|
|
379
|
+
function runDefault(node, scope) {
|
|
380
|
+
let d = node.opts.default;
|
|
381
|
+
if (typeof d === 'function' && node.kind !== 'Mixed' || (typeof d === 'function' && node.kind === 'Mixed')) d = d.call(scope, scope);
|
|
382
|
+
else d = clone(d);
|
|
383
|
+
return d;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
function applyDefaults(schema, doc, scope) {
|
|
387
|
+
for (const [path, node] of Object.entries(schema.paths)) {
|
|
388
|
+
if (path === '_id') continue;
|
|
389
|
+
if (engine.getPath(doc, path) !== undefined) continue;
|
|
390
|
+
let value;
|
|
391
|
+
if (node.opts.default !== undefined) value = runDefault(node, scope || doc);
|
|
392
|
+
else if (node.kind === 'Array') value = [];
|
|
393
|
+
else continue;
|
|
394
|
+
if (value === undefined) continue;
|
|
395
|
+
value = applySetters({ ...node, opts: { ...node.opts, set: undefined } }, value, path, doc);
|
|
396
|
+
engine.setPath(doc, path, value);
|
|
397
|
+
}
|
|
398
|
+
// subdocuments: apply their own defaults
|
|
399
|
+
for (const [path, node] of Object.entries(schema.paths)) {
|
|
400
|
+
const val = engine.getPath(doc, path);
|
|
401
|
+
if (node.kind === 'Embedded' && isObj(val)) { applyDefaults(node.schema, val, val); ensureSubId(node.schema, val); }
|
|
402
|
+
else if (node.kind === 'Array' && node.of.kind === 'Embedded' && Array.isArray(val)) for (const el of val) if (isObj(el)) { applyDefaults(node.of.schema, el, el); ensureSubId(node.of.schema, el); }
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
function ensureSubId(schema, obj) { if (schema.paths._id && obj._id === undefined) obj._id = new ObjectId(); }
|
|
406
|
+
|
|
407
|
+
// ---------- hydrate / serialize ----------
|
|
408
|
+
function hydrateValue(node, v) {
|
|
409
|
+
if (v === null || v === undefined) return v;
|
|
410
|
+
switch (node.kind) {
|
|
411
|
+
case 'Date': return v instanceof Date ? v : new Date(v);
|
|
412
|
+
case 'ObjectId': return typeof v === 'string' && ObjectId.isValid(v) ? new ObjectId(v) : v;
|
|
413
|
+
case 'Buffer': return v && v.type === 'Buffer' && Array.isArray(v.data) ? Buffer.from(v.data) : v;
|
|
414
|
+
case 'Array': {
|
|
415
|
+
if (!Array.isArray(v) || node.of.kind === 'Mixed' || node.of.kind === 'String' || node.of.kind === 'Number' || node.of.kind === 'Boolean') return v;
|
|
416
|
+
for (let i = 0; i < v.length; i++) v[i] = hydrateValue(node.of, v[i]);
|
|
417
|
+
return v;
|
|
418
|
+
}
|
|
419
|
+
case 'Map': { if (v instanceof Map || !isObj(v)) return v; const m = new Map(); for (const k of Object.keys(v)) m.set(k, hydrateValue(node.of, v[k])); return m; }
|
|
420
|
+
case 'Embedded': hydrateObject(node.schema, v); return v;
|
|
421
|
+
default: return v;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
function hydrateObject(schema, obj) {
|
|
426
|
+
if (!isObj(obj)) return obj;
|
|
427
|
+
for (const [path, node] of Object.entries(schema.paths)) {
|
|
428
|
+
const k = node.kind;
|
|
429
|
+
if (k === 'String' || k === 'Number' || k === 'Boolean' || k === 'Mixed') continue;
|
|
430
|
+
const parts = path.split('.');
|
|
431
|
+
let cur = obj;
|
|
432
|
+
for (let i = 0; i < parts.length - 1 && cur; i++) cur = cur[parts[i]];
|
|
433
|
+
if (!cur || typeof cur !== 'object') continue;
|
|
434
|
+
const last = parts[parts.length - 1];
|
|
435
|
+
if (cur[last] !== undefined) cur[last] = hydrateValue(node, cur[last]);
|
|
436
|
+
}
|
|
437
|
+
return obj;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
function replacer(key, value) { return value instanceof Map ? Object.fromEntries(value) : value; }
|
|
441
|
+
function serialize(doc) { return JSON.stringify(doc, replacer); }
|
|
442
|
+
|
|
443
|
+
// ---------- validation ----------
|
|
444
|
+
const MESSAGES = {
|
|
445
|
+
required: 'Path `{PATH}` is required.',
|
|
446
|
+
enum: '`{VALUE}` is not a valid enum value for path `{PATH}`.',
|
|
447
|
+
min: 'Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).',
|
|
448
|
+
max: 'Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).',
|
|
449
|
+
minlength: 'Path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).',
|
|
450
|
+
maxlength: 'Path `{PATH}` (`{VALUE}`) is longer than the maximum allowed length ({MAXLENGTH}).',
|
|
451
|
+
match: 'Path `{PATH}` is invalid ({VALUE}).',
|
|
452
|
+
user: 'Validator failed for path `{PATH}` with value `{VALUE}`',
|
|
453
|
+
};
|
|
454
|
+
function format(msg, props) {
|
|
455
|
+
if (typeof msg === 'function') return msg(props);
|
|
456
|
+
return msg.replace(/\{(\w+)\}/g, (m, k) => { const v = { PATH: props.path, VALUE: props.value instanceof Date ? props.value : Array.isArray(props.value) ? props.value.join(',') : props.value, MIN: props.min, MAX: props.max, MINLENGTH: props.minlength, MAXLENGTH: props.maxlength, ENUM: props.enumValues }[k]; return v === undefined ? m : String(v); });
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
function optionValue(o) { return Array.isArray(o) ? [o[0], o[1]] : [o, undefined]; }
|
|
460
|
+
|
|
461
|
+
function checkRequired(node, v) {
|
|
462
|
+
if (v === undefined || v === null) return false;
|
|
463
|
+
if (node.kind === 'String') return typeof v === 'string' && v.length > 0;
|
|
464
|
+
if (node.kind === 'Number') return typeof v === 'number' && !Number.isNaN(v);
|
|
465
|
+
if (node.kind === 'Date') return v instanceof Date;
|
|
466
|
+
return true;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
function validateNode(node, path, value, scope, errors, pending) {
|
|
470
|
+
const opts = node.opts;
|
|
471
|
+
const fail = (type, props, custom) => {
|
|
472
|
+
const properties = { type, path, value, ...props };
|
|
473
|
+
const message = custom || MESSAGES[type] || MESSAGES.user;
|
|
474
|
+
properties.message = format(message, properties);
|
|
475
|
+
errors[path] = new ValidatorError(properties);
|
|
476
|
+
};
|
|
477
|
+
if (opts.required) {
|
|
478
|
+
let [req, msg] = optionValue(opts.required);
|
|
479
|
+
if (isObj(opts.required)) { req = true; msg = opts.required.message; }
|
|
480
|
+
if (typeof req === 'function') req = req.call(scope, scope);
|
|
481
|
+
if (req && !checkRequired(node, value)) { fail('required', {}, msg); return; }
|
|
482
|
+
}
|
|
483
|
+
if (value === undefined) return;
|
|
484
|
+
if (value !== null) {
|
|
485
|
+
if (opts.enum && (node.kind === 'String' || node.kind === 'Number')) {
|
|
486
|
+
const list = node.enumValues;
|
|
487
|
+
const msg = isObj(opts.enum) && !Array.isArray(opts.enum) ? opts.enum.message : undefined;
|
|
488
|
+
if (list.length && !list.includes(value)) { fail('enum', { enumValues: list }, msg); return; }
|
|
489
|
+
}
|
|
490
|
+
if (opts.min !== undefined && (node.kind === 'Number' || node.kind === 'Date')) {
|
|
491
|
+
const [min, msg] = optionValue(opts.min); const lo = typeof min === 'function' ? min.call(scope) : min;
|
|
492
|
+
if (value < lo) { fail('min', { min: lo }, msg); return; }
|
|
493
|
+
}
|
|
494
|
+
if (opts.max !== undefined && (node.kind === 'Number' || node.kind === 'Date')) {
|
|
495
|
+
const [max, msg] = optionValue(opts.max); const hi = typeof max === 'function' ? max.call(scope) : max;
|
|
496
|
+
if (value > hi) { fail('max', { max: hi }, msg); return; }
|
|
497
|
+
}
|
|
498
|
+
const minl = opts.minlength ?? opts.minLength, maxl = opts.maxlength ?? opts.maxLength;
|
|
499
|
+
if (minl !== undefined && node.kind === 'String') { const [m, msg] = optionValue(minl); if (value.length < m) { fail('minlength', { minlength: m }, msg); return; } }
|
|
500
|
+
if (maxl !== undefined && node.kind === 'String') { const [m, msg] = optionValue(maxl); if (value.length > m) { fail('maxlength', { maxlength: m }, msg); return; } }
|
|
501
|
+
if (opts.match && node.kind === 'String') {
|
|
502
|
+
const [re, msg] = optionValue(opts.match);
|
|
503
|
+
const rx = re instanceof RegExp ? re : new RegExp(re);
|
|
504
|
+
rx.lastIndex = 0;
|
|
505
|
+
if (!rx.test(value)) { fail('match', {}, msg); return; }
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
if (opts.validate) {
|
|
509
|
+
const list = Array.isArray(opts.validate) && (typeof opts.validate[1] === 'string' || (typeof opts.validate[0] === 'function' && opts.validate.length === 2 && typeof opts.validate[1] !== 'function' && !isObj(opts.validate[1]))) ? [opts.validate] : [].concat(opts.validate);
|
|
510
|
+
for (const entry of list) {
|
|
511
|
+
let validator, message, type = 'user defined';
|
|
512
|
+
if (typeof entry === 'function') validator = entry;
|
|
513
|
+
else if (Array.isArray(entry)) { [validator, message] = entry; }
|
|
514
|
+
else { validator = entry.validator; message = entry.message; type = entry.type || type; }
|
|
515
|
+
if (validator instanceof RegExp) { if (!validator.test(String(value))) { fail(type, {}, message); return; } continue; }
|
|
516
|
+
if (typeof validator !== 'function') continue;
|
|
517
|
+
let ok;
|
|
518
|
+
try { ok = validator.call(scope, value, { path, value, type }); } catch (e) { errors[path] = new ValidatorError({ type, path, value, message: e.message, reason: e }); return; }
|
|
519
|
+
if (ok && typeof ok.then === 'function') {
|
|
520
|
+
if (pending) pending.push(ok.then((res) => { if (res === false && !errors[path]) fail(type, {}, message || MESSAGES.user); }, (e) => { if (!errors[path]) errors[path] = new ValidatorError({ type, path, value, message: e.message, reason: e }); }));
|
|
521
|
+
} else if (ok === false) { fail(type, {}, message || MESSAGES.user); return; }
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
// Walks the document and runs every validator. Custom async validators are collected in `pending`.
|
|
527
|
+
function validateTree(schema, doc, scope, prefix, errors, pending, only) {
|
|
528
|
+
for (const [p, node] of Object.entries(schema.paths)) {
|
|
529
|
+
if (node.kind === 'Mixed' && !node.opts.required && !node.opts.validate) continue;
|
|
530
|
+
const path = prefix ? `${prefix}.${p}` : p;
|
|
531
|
+
if (only && !only.has(path) && !only.has(p) && !node.opts.required) continue;
|
|
532
|
+
const value = engine.getPath(doc, p);
|
|
533
|
+
validateNode(node, path, value, scope, errors, pending);
|
|
534
|
+
if (value === undefined || value === null) continue;
|
|
535
|
+
if (node.kind === 'Embedded' && isObj(value)) validateTree(node.schema, value, value, path, errors, pending);
|
|
536
|
+
else if (node.kind === 'Array') {
|
|
537
|
+
if (node.of.kind === 'Embedded') value.forEach((el, i) => { if (isObj(el)) validateTree(node.of.schema, el, el, `${path}.${i}`, errors, pending); });
|
|
538
|
+
else if (node.of.kind !== 'Mixed' && (node.of.opts.enum || node.of.opts.min !== undefined || node.of.opts.max !== undefined || node.of.opts.match || node.of.opts.validate || node.of.opts.maxlength !== undefined || node.of.opts.minlength !== undefined)) value.forEach((el, i) => validateNode(node.of, `${path}.${i}`, el, scope, errors, pending));
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
async function validateDocument(schema, doc, scope, only) {
|
|
544
|
+
const errors = {}, pending = [];
|
|
545
|
+
validateTree(schema, doc, scope, '', errors, pending, only);
|
|
546
|
+
if (pending.length) await Promise.all(pending);
|
|
547
|
+
return errors;
|
|
548
|
+
}
|
|
549
|
+
function validateDocumentSync(schema, doc, scope, only) {
|
|
550
|
+
const errors = {};
|
|
551
|
+
validateTree(schema, doc, scope, '', errors, null, only);
|
|
552
|
+
return errors;
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
module.exports = { Schema, VirtualType, Types, castValue, castLeaf, castDocument, applySetters, applyDefaults, hydrateObject, hydrateValue, serialize, validateDocument, validateDocumentSync, validateNode, makeNode, kindOf, SchemaTypeMarker, ensureSubId, replacer };
|