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/document.js
ADDED
|
@@ -0,0 +1,476 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const util = require('util');
|
|
3
|
+
const engine = require('./engine');
|
|
4
|
+
const ObjectId = require('./objectid');
|
|
5
|
+
const S = require('./schema');
|
|
6
|
+
const { ValidationError, DocumentNotFoundError, CastError } = require('./errors');
|
|
7
|
+
|
|
8
|
+
const { isObj, clone } = engine;
|
|
9
|
+
const HYDRATE = Symbol('blackhole.hydrate');
|
|
10
|
+
|
|
11
|
+
// ---------- hooks ----------
|
|
12
|
+
// Runs schema middleware. `fn(next)` style, promise style and sync style are all supported.
|
|
13
|
+
async function runHooks(schema, kind, event, ctx, args = []) {
|
|
14
|
+
const hooks = schema.hooksFor(kind, event);
|
|
15
|
+
for (const h of hooks) {
|
|
16
|
+
const fn = h.fn;
|
|
17
|
+
if (kind === 'pre') {
|
|
18
|
+
if (fn.length >= 1 && !(fn.length === 1 && fn.constructor.name === 'AsyncFunction')) {
|
|
19
|
+
await new Promise((resolve, reject) => {
|
|
20
|
+
let done = false;
|
|
21
|
+
const next = (err) => { if (done) return; done = true; err ? reject(err) : resolve(); };
|
|
22
|
+
let ret;
|
|
23
|
+
try { ret = fn.call(ctx, next, ...args); } catch (e) { return reject(e); }
|
|
24
|
+
if (ret && typeof ret.then === 'function') ret.then(() => next(), (e) => { done = true; reject(e); });
|
|
25
|
+
});
|
|
26
|
+
} else {
|
|
27
|
+
await fn.call(ctx);
|
|
28
|
+
}
|
|
29
|
+
} else {
|
|
30
|
+
if (fn.length >= 3) continue; // error handling middleware: only used on failures
|
|
31
|
+
if (fn.length === 2) {
|
|
32
|
+
await new Promise((resolve, reject) => {
|
|
33
|
+
let ret;
|
|
34
|
+
try { ret = fn.call(ctx, args[0], (err) => (err ? reject(err) : resolve())); } catch (e) { return reject(e); }
|
|
35
|
+
if (ret && typeof ret.then === 'function') ret.then(resolve, reject);
|
|
36
|
+
});
|
|
37
|
+
} else await fn.call(ctx, args[0]);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
async function runErrorHooks(schema, event, ctx, error) {
|
|
42
|
+
for (const h of schema.hooksFor('post', event)) {
|
|
43
|
+
if (h.fn.length === 3) {
|
|
44
|
+
let handled = false;
|
|
45
|
+
await new Promise((resolve, reject) => { h.fn.call(ctx, error, undefined, (err) => { if (err) { error = err; } handled = true; resolve(); }); });
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return error;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// ---------- change tracking proxies ----------
|
|
52
|
+
const TRACKED = new WeakMap();
|
|
53
|
+
const ARRAY_EXTRAS = new Set(['addToSet', 'pull', 'remove', 'nonAtomicPush', 'set', 'id', 'create', 'toObject', 'isblackholeArray', 'inspect', '$push', '$pull']);
|
|
54
|
+
|
|
55
|
+
function track(doc, root, value, path = root) {
|
|
56
|
+
if (value === null || typeof value !== 'object') return value;
|
|
57
|
+
const isArr = Array.isArray(value);
|
|
58
|
+
if (!isArr && !isObj(value)) return value;
|
|
59
|
+
let perDoc = TRACKED.get(doc);
|
|
60
|
+
if (!perDoc) { perDoc = new WeakMap(); TRACKED.set(doc, perDoc); }
|
|
61
|
+
let p = perDoc.get(value);
|
|
62
|
+
if (p) return p;
|
|
63
|
+
const schemaRef = doc.$__.schema;
|
|
64
|
+
const proxy = new Proxy(value, {
|
|
65
|
+
get(target, prop, receiver) {
|
|
66
|
+
if (isArr && typeof prop === 'string' && ARRAY_EXTRAS.has(prop) && !(prop in Array.prototype && prop !== 'set')) return arrayExtra(doc, root, target, proxy, prop);
|
|
67
|
+
if (prop === 'isblackholeArray') return isArr;
|
|
68
|
+
const v = Reflect.get(target, prop, receiver);
|
|
69
|
+
if (typeof prop === 'symbol') return v;
|
|
70
|
+
if (v === null || typeof v !== 'object') return v;
|
|
71
|
+
const childPath = !isArr && (schemaRef.nested[`${path}.${prop}`] || schemaRef.paths[`${path}.${prop}`]) ? `${path}.${prop}` : path;
|
|
72
|
+
return track(doc, root, v, childPath);
|
|
73
|
+
},
|
|
74
|
+
set(target, prop, v, receiver) {
|
|
75
|
+
if (isArr && typeof prop === 'string' && /^\d+$/.test(prop)) {
|
|
76
|
+
const node = doc.$__.schema.paths[root];
|
|
77
|
+
if (node && node.kind === 'Array' && node.of.kind !== 'Mixed') v = S.castValue(node.of, v, `${root}.${prop}`);
|
|
78
|
+
}
|
|
79
|
+
const ok = Reflect.set(target, prop, v, receiver);
|
|
80
|
+
const full = `${path}.${String(prop)}`;
|
|
81
|
+
doc.markModified(!isArr && (schemaRef.paths[full] || schemaRef.nested[full]) ? full : path);
|
|
82
|
+
return ok;
|
|
83
|
+
},
|
|
84
|
+
deleteProperty(target, prop) { const ok = Reflect.deleteProperty(target, prop); const full = `${path}.${String(prop)}`; doc.markModified(!isArr && (schemaRef.paths[full] || schemaRef.nested[full]) ? full : path); return ok; },
|
|
85
|
+
});
|
|
86
|
+
perDoc.set(value, proxy);
|
|
87
|
+
return proxy;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function arrayExtra(doc, root, target, proxy, prop) {
|
|
91
|
+
const node = doc.$__.schema.paths[root];
|
|
92
|
+
const cast = (v) => (node && node.kind === 'Array' && node.of.kind !== 'Mixed' ? S.castValue(node.of, v, root) : v);
|
|
93
|
+
switch (prop) {
|
|
94
|
+
case 'addToSet': return (...items) => { const added = []; for (const raw of items) { const v = cast(raw); if (!target.some((x) => engine.eq(x, v))) { target.push(v); added.push(v); } } doc.markModified(root); return added; };
|
|
95
|
+
case 'pull': case 'remove': case '$pull': return (...items) => { for (const raw of items) { const v = cast(raw); for (let i = target.length - 1; i >= 0; i--) if (engine.eq(target[i], v) || (isObj(v) && isObj(target[i]) && engine.matches(target[i], v))) target.splice(i, 1); } doc.markModified(root); return proxy; };
|
|
96
|
+
case 'nonAtomicPush': case '$push': return (...items) => { target.push(...items.map(cast)); doc.markModified(root); return target.length; };
|
|
97
|
+
case 'set': return (i, v) => { target[i] = cast(v); doc.markModified(root); return proxy; };
|
|
98
|
+
case 'id': return (id) => track(doc, root, target.find((el) => el && el._id !== undefined && String(el._id) === String(id)) || null);
|
|
99
|
+
case 'create': return (obj) => { const sub = node && node.of.schema ? S.castDocument(node.of.schema, obj) : { ...obj }; if (node && node.of.schema) { S.applyDefaults(node.of.schema, sub, sub); S.ensureSubId(node.of.schema, sub); } return sub; };
|
|
100
|
+
case 'toObject': return () => clone(target);
|
|
101
|
+
default: return undefined;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function minimize(obj) {
|
|
106
|
+
if (!isObj(obj)) return obj;
|
|
107
|
+
for (const k of Object.keys(obj)) {
|
|
108
|
+
const v = obj[k];
|
|
109
|
+
if (isObj(v)) { minimize(v); if (Object.keys(v).length === 0) delete obj[k]; }
|
|
110
|
+
}
|
|
111
|
+
return obj;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Paths that are modified in a set of paths. A parent counts as modified when a child is.
|
|
115
|
+
function isModifiedPath(set, path) {
|
|
116
|
+
if (set.has(path)) return true;
|
|
117
|
+
for (const m of set) if (m.startsWith(`${path}.`) || path.startsWith(`${m}.`)) return true;
|
|
118
|
+
return false;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function rootOf(schema, path) {
|
|
122
|
+
// "meta.a" with nested root "meta" stays "meta.a"; array/subdoc children collapse to the array path
|
|
123
|
+
const parts = path.split('.');
|
|
124
|
+
for (let i = 1; i <= parts.length; i++) {
|
|
125
|
+
const p = parts.slice(0, i).join('.');
|
|
126
|
+
const node = schema.paths[p];
|
|
127
|
+
if (node) return p;
|
|
128
|
+
}
|
|
129
|
+
return path;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
class Document {
|
|
133
|
+
constructor(obj, fields, skipId) {
|
|
134
|
+
const Model = this.constructor;
|
|
135
|
+
const schema = Model.schema;
|
|
136
|
+
const state = { schema, model: Model, isNew: true, modified: new Set(), populated: new Map(), selected: null, errors: undefined, saving: false, init: false };
|
|
137
|
+
Object.defineProperty(this, '$__', { value: state, enumerable: false, writable: true });
|
|
138
|
+
Object.defineProperty(this, '_doc', { value: {}, enumerable: false, writable: true });
|
|
139
|
+
Object.defineProperty(this, '$locals', { value: {}, enumerable: false, writable: true });
|
|
140
|
+
Object.defineProperty(this, '$op', { value: null, enumerable: false, writable: true });
|
|
141
|
+
const proxy = new Proxy(this, handlerFor(schema));
|
|
142
|
+
state.proxy = proxy;
|
|
143
|
+
if (obj === HYDRATE) {
|
|
144
|
+
this._doc = fields;
|
|
145
|
+
state.isNew = false;
|
|
146
|
+
state.init = true;
|
|
147
|
+
state.selected = skipId || null;
|
|
148
|
+
return proxy;
|
|
149
|
+
}
|
|
150
|
+
if (obj && typeof obj === 'object') {
|
|
151
|
+
if (obj.$isblackholeDocument) obj = obj.toObject();
|
|
152
|
+
proxy.$set(obj);
|
|
153
|
+
}
|
|
154
|
+
S.applyDefaults(schema, this._doc, proxy);
|
|
155
|
+
if (schema.paths._id && this._doc._id === undefined) this._doc._id = new ObjectId();
|
|
156
|
+
if (schema.options.versionKey && this._doc[schema.options.versionKey] === undefined && !skipId) this._doc[schema.options.versionKey] = 0;
|
|
157
|
+
return proxy;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
get $isblackholeDocument() { return true; }
|
|
161
|
+
get $isNew() { return this.$__.isNew; }
|
|
162
|
+
get isNew() { return this.$__.isNew; }
|
|
163
|
+
set isNew(v) { this.$__.isNew = !!v; }
|
|
164
|
+
get errors() { return this.$__.errors; }
|
|
165
|
+
get schema() { return this.$__.schema; }
|
|
166
|
+
get db() { return this.constructor.db; }
|
|
167
|
+
get collection() { return this.constructor.collection; }
|
|
168
|
+
get id() {
|
|
169
|
+
const s = this.$__.schema;
|
|
170
|
+
if (s.options.id === false || s.paths.id) return undefined;
|
|
171
|
+
const v = this._doc._id;
|
|
172
|
+
return v === undefined || v === null ? v : String(v);
|
|
173
|
+
}
|
|
174
|
+
get $__delta() { return undefined; }
|
|
175
|
+
|
|
176
|
+
// ----- reading -----
|
|
177
|
+
$isDeleted(v) { if (v !== undefined) this.$__.deleted = !!v; return !!this.$__.deleted; }
|
|
178
|
+
get(path, type, options = {}) {
|
|
179
|
+
const state = this.$__;
|
|
180
|
+
if (state.populated.has(path)) return state.populated.get(path);
|
|
181
|
+
const virtual = state.schema.virtuals[path];
|
|
182
|
+
if (virtual) return virtual.applyGetters(undefined, this.$__.proxy);
|
|
183
|
+
if (path === 'id' && !state.schema.paths.id) return this.id;
|
|
184
|
+
let v = engine.getPath(this._doc, path);
|
|
185
|
+
const node = state.schema.path(path);
|
|
186
|
+
if (node && node.opts.get && options.getters !== false) v = node.opts.get.call(this.$__.proxy, v, node);
|
|
187
|
+
return v;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// ----- writing -----
|
|
191
|
+
set(path, value, type, options) {
|
|
192
|
+
const state = this.$__;
|
|
193
|
+
const schema = state.schema;
|
|
194
|
+
if (path && typeof path === 'object') {
|
|
195
|
+
const src = path.$isblackholeDocument ? path.toObject() : path;
|
|
196
|
+
const opts = value && typeof value === 'object' ? value : type;
|
|
197
|
+
for (const k of Object.keys(src)) this.set(k, src[k], undefined, opts);
|
|
198
|
+
return this.$__.proxy;
|
|
199
|
+
}
|
|
200
|
+
if (typeof path !== 'string') return this.$__.proxy;
|
|
201
|
+
const virtual = schema.virtuals[path];
|
|
202
|
+
if (virtual) { virtual.applySetters(value, this.$__.proxy); return this.$__.proxy; }
|
|
203
|
+
if (value && value.$isblackholeDocument) value = value.toObject();
|
|
204
|
+
const node = schema.path(path);
|
|
205
|
+
const direct = schema.paths[path];
|
|
206
|
+
if (direct) {
|
|
207
|
+
const oldValue = engine.getPath(this._doc, path);
|
|
208
|
+
if (direct.opts.immutable && !state.isNew && oldValue !== undefined && (typeof direct.opts.immutable !== 'function' || direct.opts.immutable.call(state.proxy, oldValue))) {
|
|
209
|
+
if (schema.options.strict === 'throw') throw new Error(`Path \`${path}\` is immutable and strict mode is set to throw.`);
|
|
210
|
+
return state.proxy;
|
|
211
|
+
}
|
|
212
|
+
if (value === undefined) { if (oldValue !== undefined) { engine.unsetPath(this._doc, path); this.markModified(path); } return state.proxy; }
|
|
213
|
+
const cast = S.applySetters(direct, value, path, state.proxy);
|
|
214
|
+
if (oldValue !== undefined && state.init && engine.eq(oldValue, cast) && !state.modified.has(path)) return state.proxy;
|
|
215
|
+
engine.setPath(this._doc, path, cast);
|
|
216
|
+
state.populated.delete(path);
|
|
217
|
+
this.markModified(path);
|
|
218
|
+
return state.proxy;
|
|
219
|
+
}
|
|
220
|
+
if (schema.nested[path]) {
|
|
221
|
+
if (value === null || value === undefined) { engine.setPath(this._doc, path, value === null ? null : undefined); this.markModified(path); return state.proxy; }
|
|
222
|
+
if (isObj(value)) { for (const k of Object.keys(value)) this.set(`${path}.${k}`, value[k], undefined, options); return state.proxy; }
|
|
223
|
+
}
|
|
224
|
+
if (node) {
|
|
225
|
+
// path inside an array / subdocument / map
|
|
226
|
+
const cast = value === undefined ? undefined : node.kind === 'Mixed' ? value : S.castValue(node, value, path);
|
|
227
|
+
engine.setPath(this._doc, path, cast);
|
|
228
|
+
this.markModified(rootOf(schema, path));
|
|
229
|
+
return state.proxy;
|
|
230
|
+
}
|
|
231
|
+
// not in schema
|
|
232
|
+
const rootPath = path.split('.')[0];
|
|
233
|
+
if (schema.paths[rootPath] && schema.paths[rootPath].kind === 'Mixed') { engine.setPath(this._doc, path, value); this.markModified(rootPath); return state.proxy; }
|
|
234
|
+
if (schema.nested[rootPath] || schema.options.strict === false || (options && options.strict === false)) {
|
|
235
|
+
if (schema.options.strict === false || (options && options.strict === false)) { engine.setPath(this._doc, path, value); this.markModified(path); }
|
|
236
|
+
else if (schema.options.strict === 'throw') throw new (require('./errors').StrictModeError)(path);
|
|
237
|
+
return state.proxy;
|
|
238
|
+
}
|
|
239
|
+
if (schema.options.strict === 'throw') throw new (require('./errors').StrictModeError)(path);
|
|
240
|
+
return state.proxy;
|
|
241
|
+
}
|
|
242
|
+
$set(path, value, type, options) { return this.set(path, value, type, options); }
|
|
243
|
+
|
|
244
|
+
// ----- change tracking -----
|
|
245
|
+
markModified(path) { this.$__.modified.add(path); }
|
|
246
|
+
unmarkModified(path) { this.$__.modified.delete(path); }
|
|
247
|
+
isModified(paths) {
|
|
248
|
+
const set = this.$__.modified;
|
|
249
|
+
if (paths === undefined) return set.size > 0;
|
|
250
|
+
const list = typeof paths === 'string' ? paths.split(' ') : paths;
|
|
251
|
+
return list.some((p) => isModifiedPath(set, p));
|
|
252
|
+
}
|
|
253
|
+
isDirectModified(path) { return this.$__.modified.has(path); }
|
|
254
|
+
modifiedPaths() {
|
|
255
|
+
const out = new Set();
|
|
256
|
+
for (const m of this.$__.modified) { const parts = m.split('.'); for (let i = 1; i <= parts.length; i++) out.add(parts.slice(0, i).join('.')); }
|
|
257
|
+
return [...out];
|
|
258
|
+
}
|
|
259
|
+
directModifiedPaths() { return [...this.$__.modified]; }
|
|
260
|
+
isInit(path) { return this.$__.init && !this.$__.modified.has(path); }
|
|
261
|
+
isSelected(path) {
|
|
262
|
+
const sel = this.$__.selected;
|
|
263
|
+
if (!sel) return true;
|
|
264
|
+
const incl = Object.entries(sel).filter(([k, v]) => v && k !== '_id');
|
|
265
|
+
if (incl.length) return incl.some(([k]) => path === k || path.startsWith(`${k}.`) || k.startsWith(`${path}.`));
|
|
266
|
+
return !Object.entries(sel).some(([k, v]) => !v && (path === k || path.startsWith(`${k}.`)));
|
|
267
|
+
}
|
|
268
|
+
populated(path) { const v = this.$__.populated.get(path); return v === undefined ? undefined : Array.isArray(v) ? v.map((x) => x && x._id) : v && v._id; }
|
|
269
|
+
depopulate(path) { if (path) this.$__.populated.delete(path); else this.$__.populated.clear(); return this.$__.proxy; }
|
|
270
|
+
equals(other) { return !!other && other._id !== undefined && String(other._id) === String(this._doc._id); }
|
|
271
|
+
$clone() { return this.$__.model.hydrate(this.toObject()); }
|
|
272
|
+
$isDefault(path) { return false; }
|
|
273
|
+
$ignore(path) { this.$__.modified.delete(path); }
|
|
274
|
+
$session() { return null; }
|
|
275
|
+
inspect() { return this.toObject({ virtuals: false }); }
|
|
276
|
+
[util.inspect.custom](depth, options) { return `${this.$__.model.modelName} ${util.inspect(this.toObject({ virtuals: false }), options)}`; }
|
|
277
|
+
unmarkAll() { this.$__.modified.clear(); }
|
|
278
|
+
|
|
279
|
+
// ----- output -----
|
|
280
|
+
toObject(options = {}) {
|
|
281
|
+
const state = this.$__;
|
|
282
|
+
const schema = state.schema;
|
|
283
|
+
const defaults = options._isJSON ? schema.options.toJSON : schema.options.toObject;
|
|
284
|
+
const o = { ...(defaults || {}), ...options };
|
|
285
|
+
let out = clone(this._doc);
|
|
286
|
+
if (!o.depopulate) for (const [path, value] of state.populated) {
|
|
287
|
+
const plain = Array.isArray(value) ? value.map((v) => (v && v.$isblackholeDocument ? v.toObject({ ...o, _isJSON: options._isJSON }) : v)) : value && value.$isblackholeDocument ? value.toObject({ ...o, _isJSON: options._isJSON }) : value;
|
|
288
|
+
engine.setPath(out, path, plain);
|
|
289
|
+
}
|
|
290
|
+
if (o.getters || o.virtuals) {
|
|
291
|
+
if (o.getters) for (const [path, node] of Object.entries(schema.paths)) if (node.opts.get) { const v = engine.getPath(out, path); if (v !== undefined || true) engine.setPath(out, path, node.opts.get.call(state.proxy, v, node)); }
|
|
292
|
+
if (o.virtuals !== false) for (const [name, v] of Object.entries(schema.virtuals)) if (v.getters.length && (o.virtuals || (o.getters && false))) {
|
|
293
|
+
const val = v.applyGetters(undefined, state.proxy);
|
|
294
|
+
if (val !== undefined) engine.setPath(out, name, val);
|
|
295
|
+
}
|
|
296
|
+
if (o.virtuals && schema.options.id !== false && !schema.paths.id && out._id !== undefined) out.id = String(out._id);
|
|
297
|
+
}
|
|
298
|
+
if (o.minimize !== false && schema.options.minimize !== false) minimize(out);
|
|
299
|
+
if (o.versionKey === false && schema.options.versionKey) delete out[schema.options.versionKey];
|
|
300
|
+
if (o.flattenMaps) flattenMaps(out);
|
|
301
|
+
if (o.flattenObjectIds) out = JSON.parse(JSON.stringify(out));
|
|
302
|
+
const transform = o.transform === true ? undefined : o.transform;
|
|
303
|
+
if (typeof transform === 'function') { const r = transform(state.proxy, out, o); if (r !== undefined) out = r; }
|
|
304
|
+
return out;
|
|
305
|
+
}
|
|
306
|
+
toJSON(options = {}) {
|
|
307
|
+
const o = { flattenMaps: true, ...options, _isJSON: true };
|
|
308
|
+
const defaults = this.$__.schema.options.toJSON;
|
|
309
|
+
if (defaults && defaults.flattenMaps === false) o.flattenMaps = false;
|
|
310
|
+
return this.toObject(o);
|
|
311
|
+
}
|
|
312
|
+
toString() { return util.inspect(this); }
|
|
313
|
+
|
|
314
|
+
// ----- validation -----
|
|
315
|
+
async validate(pathsToValidate, options) {
|
|
316
|
+
const state = this.$__;
|
|
317
|
+
await runHooks(state.schema, 'pre', 'validate', state.proxy);
|
|
318
|
+
normalize(this);
|
|
319
|
+
let only;
|
|
320
|
+
if (pathsToValidate) only = new Set([].concat(pathsToValidate).flatMap((p) => (typeof p === 'string' ? p.split(' ') : p)));
|
|
321
|
+
else if (!state.isNew) only = new Set([...this.modifiedPaths()]);
|
|
322
|
+
const errors = await S.validateDocument(state.schema, this._doc, state.proxy, only);
|
|
323
|
+
if (Object.keys(errors).length) {
|
|
324
|
+
const err = new ValidationError(state.proxy);
|
|
325
|
+
err.message = `${state.model.modelName} validation failed`;
|
|
326
|
+
for (const [p, e] of Object.entries(errors)) err.addError(p, e);
|
|
327
|
+
err.message = `${state.model.modelName} validation failed: ${Object.values(errors).map((e) => `${e.path}: ${e.message}`).join(', ')}`;
|
|
328
|
+
state.errors = err.errors;
|
|
329
|
+
throw err;
|
|
330
|
+
}
|
|
331
|
+
state.errors = undefined;
|
|
332
|
+
await runHooks(state.schema, 'post', 'validate', state.proxy, [state.proxy]);
|
|
333
|
+
}
|
|
334
|
+
validateSync(pathsToValidate) {
|
|
335
|
+
const state = this.$__;
|
|
336
|
+
normalize(this);
|
|
337
|
+
let only;
|
|
338
|
+
if (pathsToValidate) only = new Set([].concat(pathsToValidate));
|
|
339
|
+
else if (!state.isNew) only = new Set([...this.modifiedPaths()]);
|
|
340
|
+
const errors = S.validateDocumentSync(state.schema, this._doc, state.proxy, only);
|
|
341
|
+
if (!Object.keys(errors).length) return undefined;
|
|
342
|
+
const err = new ValidationError(state.proxy);
|
|
343
|
+
for (const [p, e] of Object.entries(errors)) err.addError(p, e);
|
|
344
|
+
err.message = `${state.model.modelName} validation failed: ${Object.values(errors).map((e) => `${e.path}: ${e.message}`).join(', ')}`;
|
|
345
|
+
return err;
|
|
346
|
+
}
|
|
347
|
+
invalidate(path, message) { return undefined; }
|
|
348
|
+
|
|
349
|
+
// ----- persistence -----
|
|
350
|
+
async save(options = {}) {
|
|
351
|
+
const state = this.$__;
|
|
352
|
+
const proxy = state.proxy;
|
|
353
|
+
const Model = state.model;
|
|
354
|
+
const schema = state.schema;
|
|
355
|
+
if (state.saving) throw new Error('Can\'t save() the same doc multiple times in parallel. Document: ' + this._doc._id);
|
|
356
|
+
state.saving = true;
|
|
357
|
+
try {
|
|
358
|
+
if (options.validateBeforeSave !== false && schema.options.validateBeforeSave !== false) await this.validate();
|
|
359
|
+
await runHooks(schema, 'pre', 'save', proxy);
|
|
360
|
+
normalize(this);
|
|
361
|
+
const result = Model.$persist(proxy, options);
|
|
362
|
+
await runHooks(schema, 'post', 'save', proxy, [proxy]);
|
|
363
|
+
return result;
|
|
364
|
+
} catch (e) {
|
|
365
|
+
const err = await runErrorHooks(schema, 'save', proxy, e);
|
|
366
|
+
throw err;
|
|
367
|
+
} finally {
|
|
368
|
+
state.saving = false;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
async deleteOne(options) {
|
|
372
|
+
const state = this.$__;
|
|
373
|
+
const proxy = state.proxy;
|
|
374
|
+
await runHooks(state.schema, 'pre', 'deleteOne', proxy);
|
|
375
|
+
await runHooks(state.schema, 'pre', 'remove', proxy);
|
|
376
|
+
state.model.$collection.load();
|
|
377
|
+
state.model.$collection.remove(this._doc._id);
|
|
378
|
+
state.deleted = true;
|
|
379
|
+
await runHooks(state.schema, 'post', 'deleteOne', proxy, [proxy]);
|
|
380
|
+
await runHooks(state.schema, 'post', 'remove', proxy, [proxy]);
|
|
381
|
+
return proxy;
|
|
382
|
+
}
|
|
383
|
+
remove(options) { return this.deleteOne(options); }
|
|
384
|
+
updateOne(update, options) { return this.$__.model.updateOne({ _id: this._doc._id }, update, options); }
|
|
385
|
+
replaceOne(replacement, options) { return this.$__.model.replaceOne({ _id: this._doc._id }, replacement, options); }
|
|
386
|
+
overwrite(obj) {
|
|
387
|
+
const keep = this._doc._id;
|
|
388
|
+
for (const k of Object.keys(this._doc)) if (k !== '_id') { delete this._doc[k]; this.markModified(k); }
|
|
389
|
+
this.set(obj);
|
|
390
|
+
this._doc._id = keep;
|
|
391
|
+
return this.$__.proxy;
|
|
392
|
+
}
|
|
393
|
+
async populate(...args) { await this.$__.model.populate(this.$__.proxy, args.length === 1 ? args[0] : args.length === 2 && typeof args[0] === 'string' && typeof args[1] === 'string' ? { path: args[0], select: args[1] } : args[0]); return this.$__.proxy; }
|
|
394
|
+
async execPopulate() { return this.$__.proxy; }
|
|
395
|
+
async init() { return this.$__.proxy; }
|
|
396
|
+
model(name) { return this.$__.model.db.model(name); }
|
|
397
|
+
parent() { return undefined; }
|
|
398
|
+
ownerDocument() { return this.$__.proxy; }
|
|
399
|
+
getChanges() { const d = {}; for (const p of this.$__.modified) d[p] = engine.getPath(this._doc, p); return { $set: d }; }
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
function flattenMaps(o) {
|
|
403
|
+
for (const k of Object.keys(o)) {
|
|
404
|
+
if (o[k] instanceof Map) { o[k] = Object.fromEntries(o[k]); }
|
|
405
|
+
if (o[k] && typeof o[k] === 'object' && !(o[k] instanceof Date) && !(o[k] instanceof ObjectId)) flattenMaps(o[k]);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// Re-cast every modified root path (no custom setters), so in-place edits are normalized before save.
|
|
410
|
+
function normalize(doc) {
|
|
411
|
+
const state = doc.$__;
|
|
412
|
+
const schema = state.schema;
|
|
413
|
+
for (const m of state.modified) {
|
|
414
|
+
const root = rootOf(schema, m);
|
|
415
|
+
const node = schema.paths[root];
|
|
416
|
+
if (!node) continue;
|
|
417
|
+
const v = engine.getPath(doc._doc, root);
|
|
418
|
+
if (v === undefined || v === null || node.kind === 'Mixed') continue;
|
|
419
|
+
const cast = S.castValue(node, v, root);
|
|
420
|
+
engine.setPath(doc._doc, root, node.kind === 'String' ? S.applySetters({ ...node, opts: { ...node.opts, set: undefined } }, cast, root, doc) : cast);
|
|
421
|
+
if (node.kind === 'Array' && node.of.kind === 'Embedded') for (const el of engine.getPath(doc._doc, root) || []) if (isObj(el)) { S.applyDefaults(node.of.schema, el, el); S.ensureSubId(node.of.schema, el); }
|
|
422
|
+
if (node.kind === 'Embedded') { const sub = engine.getPath(doc._doc, root); if (isObj(sub)) { S.applyDefaults(node.schema, sub, sub); S.ensureSubId(node.schema, sub); } }
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
const handlerCache = new WeakMap();
|
|
427
|
+
function handlerFor(schema) {
|
|
428
|
+
let h = handlerCache.get(schema);
|
|
429
|
+
if (h) return h;
|
|
430
|
+
const rootKeys = new Set();
|
|
431
|
+
const compute = () => {
|
|
432
|
+
rootKeys.clear();
|
|
433
|
+
for (const p of Object.keys(schema.paths)) rootKeys.add(p.split('.')[0]);
|
|
434
|
+
for (const p of Object.keys(schema.nested)) rootKeys.add(p.split('.')[0]);
|
|
435
|
+
for (const v of Object.keys(schema.virtuals)) rootKeys.add(v);
|
|
436
|
+
};
|
|
437
|
+
compute();
|
|
438
|
+
const RESERVED = new Set(['constructor', 'schema', 'isNew', 'errors', 'db', 'collection', '$isNew', '$isblackholeDocument', 'save', 'get', 'set', 'toObject', 'toJSON', 'validate', 'populate']);
|
|
439
|
+
h = {
|
|
440
|
+
get(target, prop, receiver) {
|
|
441
|
+
if (typeof prop === 'symbol') return Reflect.get(target, prop, receiver);
|
|
442
|
+
if (rootKeys.size !== Object.keys(schema.paths).length + Object.keys(schema.nested).length + Object.keys(schema.virtuals).length && false) compute();
|
|
443
|
+
if (rootKeys.has(prop) && !(RESERVED.has(prop) && !(prop in schema.paths) && !(prop in schema.virtuals) && !(prop in schema.nested))) {
|
|
444
|
+
const state = target.$__;
|
|
445
|
+
if (state.populated.has(prop)) return state.populated.get(prop);
|
|
446
|
+
const virtual = schema.virtuals[prop];
|
|
447
|
+
if (virtual && !schema.paths[prop]) return virtual.applyGetters(undefined, receiver);
|
|
448
|
+
let v = target._doc[prop];
|
|
449
|
+
const node = schema.paths[prop];
|
|
450
|
+
if (node && node.opts.get) v = node.opts.get.call(receiver, v, node);
|
|
451
|
+
if (v !== null && typeof v === 'object') return track(receiver, prop, v);
|
|
452
|
+
return v;
|
|
453
|
+
}
|
|
454
|
+
return Reflect.get(target, prop, receiver);
|
|
455
|
+
},
|
|
456
|
+
set(target, prop, value, receiver) {
|
|
457
|
+
if (typeof prop === 'symbol') return Reflect.set(target, prop, value, receiver);
|
|
458
|
+
if (rootKeys.has(prop) || (!(prop in target) && (schema.options.strict === false))) {
|
|
459
|
+
if (prop === '_id' && !target.$__.isNew && false) return true;
|
|
460
|
+
target.$__.proxy.set(prop, value);
|
|
461
|
+
return true;
|
|
462
|
+
}
|
|
463
|
+
if (prop === 'id' && !schema.paths.id) return true;
|
|
464
|
+
return Reflect.set(target, prop, value, receiver);
|
|
465
|
+
},
|
|
466
|
+
has(target, prop) { return rootKeys.has(prop) || Reflect.has(target, prop); },
|
|
467
|
+
deleteProperty(target, prop) {
|
|
468
|
+
if (rootKeys.has(prop)) { target.$__.proxy.set(prop, undefined); return true; }
|
|
469
|
+
return Reflect.deleteProperty(target, prop);
|
|
470
|
+
},
|
|
471
|
+
};
|
|
472
|
+
handlerCache.set(schema, h);
|
|
473
|
+
return h;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
module.exports = { Document, HYDRATE, runHooks, runErrorHooks, track, normalize, minimize, rootOf };
|