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/model.js ADDED
@@ -0,0 +1,260 @@
1
+ 'use strict';
2
+ const engine = require('./engine');
3
+ const S = require('./schema');
4
+ const { Document, HYDRATE, runHooks, minimize } = require('./lib/document');
5
+ const { Query, castFilter, populateResults, normalizePopulate } = require('./lib/query');
6
+ const { Collection } = require('./lib/collection');
7
+ const { ValidationError, DocumentNotFoundError } = require('./errors');
8
+
9
+ const { isObj, clone } = engine;
10
+
11
+ class Aggregate {
12
+ constructor(model, pipeline = []) { this._model = model; this._pipeline = [...pipeline]; this.options = {}; }
13
+ append(...stages) { this._pipeline.push(...stages.flat()); return this; }
14
+ pipeline() { return this._pipeline; }
15
+ option(o) { Object.assign(this.options, o); return this; }
16
+ session() { return this; } allowDiskUse() { return this; } collation() { return this; } hint() { return this; } read() { return this; } readConcern() { return this; }
17
+ explain() { return Promise.resolve({ stages: this._pipeline }); }
18
+ model(m) { if (m === undefined) return this._model; this._model = m; return this; }
19
+ match(x) { return this.append({ $match: x }); }
20
+ group(x) { return this.append({ $group: x }); }
21
+ sort(x) { return this.append({ $sort: typeof x === 'string' ? Object.fromEntries(engine.normalizeSort(x)) : x }); }
22
+ project(x) { return this.append({ $project: typeof x === 'string' ? Object.fromEntries(x.split(/\s+/).filter(Boolean).map((f) => (f[0] === '-' ? [f.slice(1), 0] : [f, 1]))) : x }); }
23
+ limit(n) { return this.append({ $limit: n }); }
24
+ skip(n) { return this.append({ $skip: n }); }
25
+ unwind(...a) { return this.append(...a.map((x) => ({ $unwind: typeof x === 'string' && x[0] !== '$' ? `$${x}` : x }))); }
26
+ lookup(x) { return this.append({ $lookup: x }); }
27
+ addFields(x) { return this.append({ $addFields: x }); }
28
+ count(f) { return this.append({ $count: f }); }
29
+ sample(n) { return this.append({ $sample: { size: n } }); }
30
+ facet(x) { return this.append({ $facet: x }); }
31
+ sortByCount(x) { return this.append({ $sortByCount: x }); }
32
+ replaceRoot(x) { return this.append({ $replaceRoot: { newRoot: x } }); }
33
+ unionWith(x) { return this.append({ $unionWith: x }); }
34
+ then(res, rej) { return this.exec().then(res, rej); }
35
+ catch(rej) { return this.exec().catch(rej); }
36
+ finally(fn) { return this.exec().finally(fn); }
37
+ async exec() {
38
+ const model = this._model;
39
+ const col = model.$collection;
40
+ col.load();
41
+ const schema = model.schema;
42
+ await runHooks(schema, 'pre', 'aggregate', this);
43
+ let pipeline = this._pipeline;
44
+ let input;
45
+ if (pipeline.length && pipeline[0].$match && !pipeline[0].$match.$expr && !pipeline[0].$match.$where) {
46
+ // the first $match can use the id map and hash indexes
47
+ input = [...col.scan(castFilter(schema, pipeline[0].$match))];
48
+ pipeline = pipeline.slice(1);
49
+ } else input = [...col.docs.values()];
50
+ const env = { collection: (name) => model.db.$docsOf(name), vars: {} };
51
+ let out = engine.aggregate(input, pipeline, env);
52
+ out = out.map(clone);
53
+ await runHooks(schema, 'post', 'aggregate', this, [out]);
54
+ return out;
55
+ }
56
+ cursor() { const self = this; const it = (async function* () { for (const d of await self.exec()) yield d; })(); it.eachAsync = async (fn) => { for await (const d of it) await fn(d); }; it.toArray = async () => { const o = []; for await (const d of it) o.push(d); return o; }; it.close = async () => {}; return it; }
57
+ async *[Symbol.asyncIterator]() { for (const d of await this.exec()) yield d; }
58
+ }
59
+
60
+ function buildModel(db, name, schema, collectionName) {
61
+ const col = new Collection(collectionName || schema.options.collection || name, db);
62
+ col.hydrate = (row) => S.hydrateObject(schema, row);
63
+ for (const [fields, opts] of schema.indexes()) if (opts.unique) col.addUnique(fields, opts);
64
+
65
+ class QueryForModel extends Query {}
66
+ for (const [k, fn] of Object.entries(schema.query)) QueryForModel.prototype[k] = fn;
67
+
68
+ class Model extends Document {}
69
+ Object.defineProperty(Model, 'name', { value: name });
70
+ Model.modelName = name;
71
+ Model.schema = schema;
72
+ Model.db = db;
73
+ Model.base = db.blackhole;
74
+ Model.collection = {
75
+ name: col.name, collectionName: col.name, conn: db,
76
+ countDocuments: (f) => Promise.resolve(col.count(f || {})),
77
+ insertOne: async (d) => { const m = new Model(d); await m.save(); return { acknowledged: true, insertedId: m._id }; },
78
+ drop: async () => { col.load(); for (const d of [...col.docs.values()]) col.remove(d._id); return true; },
79
+ createIndex: async () => 'ok',
80
+ };
81
+ Model.discriminators = undefined;
82
+ Model.Query = QueryForModel;
83
+ Model.$collection = col;
84
+ for (const [k, fn] of Object.entries(schema.methods)) Object.defineProperty(Model.prototype, k, { value: fn, writable: true, configurable: true });
85
+ for (const [k, fn] of Object.entries(schema.statics)) Model[k] = fn;
86
+
87
+ const mk = (op, cond, proj, opts) => { const query = new QueryForModel(Model, op, cond, opts); if (proj) query.select(proj); return query; };
88
+ const upd = (op, cond, update, opts) => new QueryForModel(Model, op)._upd(op, cond, update, opts);
89
+
90
+ // ---------- persistence of documents ----------
91
+ Model.$persist = function persist(proxy, options = {}) {
92
+ const state = proxy.$__;
93
+ const raw = proxy._doc;
94
+ const ts = schema.options.timestamps;
95
+ const now = new Date();
96
+ col.load();
97
+ if (state.isNew) {
98
+ if (ts && options.timestamps !== false) {
99
+ if (ts.createdAt && raw[ts.createdAt] === undefined) raw[ts.createdAt] = now;
100
+ if (ts.updatedAt && raw[ts.updatedAt] === undefined) raw[ts.updatedAt] = now;
101
+ }
102
+ const stored = clone(raw);
103
+ if (schema.options.minimize !== false) minimize(stored);
104
+ col.insert(stored);
105
+ state.isNew = false;
106
+ state.init = true;
107
+ } else {
108
+ if (state.deleted) throw new DocumentNotFoundError({ _id: raw._id }, name);
109
+ const modified = [...state.modified];
110
+ if (!modified.length) return proxy;
111
+ const existing = col.getById(raw._id);
112
+ if (!existing) throw new DocumentNotFoundError({ _id: raw._id }, name);
113
+ if (ts && ts.updatedAt && options.timestamps !== false && !state.modified.has(ts.updatedAt)) { raw[ts.updatedAt] = now; modified.push(ts.updatedAt); }
114
+ const next = clone(existing);
115
+ for (const m of modified) {
116
+ const v = engine.getPath(raw, m);
117
+ if (v === undefined) engine.unsetPath(next, m); else engine.setPath(next, m, clone(v));
118
+ }
119
+ if (schema.options.minimize !== false) minimize(next);
120
+ col.replace(next, existing);
121
+ }
122
+ state.modified.clear();
123
+ return proxy;
124
+ };
125
+
126
+ Model.$hydrate = function hydrateDoc(plain, proj) {
127
+ const doc = Reflect.construct(Model, [HYDRATE, plain, proj || null]);
128
+ const exclusionOnly = !proj || !Object.entries(proj).some(([k, v]) => k !== '_id' && !isObj(v) && v);
129
+ if (exclusionOnly) S.applyDefaults(schema, plain, doc);
130
+ return doc;
131
+ };
132
+ Model.hydrate = (obj, projection) => Model.$hydrate(S.hydrateObject(schema, clone(obj)), projection);
133
+
134
+ // ---------- finders ----------
135
+ Model.find = (cond, proj, opts) => mk('find', cond, proj, opts);
136
+ Model.findOne = (cond, proj, opts) => mk('findOne', cond, proj, opts);
137
+ Model.findById = (id, proj, opts) => mk('findOne', { _id: id }, proj, opts);
138
+ Model.where = (...args) => { const query = new QueryForModel(Model, 'find'); return args.length ? query.where(...args) : query; };
139
+ Model.countDocuments = (cond, opts) => mk('countDocuments', cond, null, opts);
140
+ Model.count = (cond, opts) => mk('countDocuments', cond, null, opts);
141
+ Model.estimatedDocumentCount = (opts) => mk('estimatedDocumentCount', null, null, opts);
142
+ Model.distinct = (field, cond) => new QueryForModel(Model, 'distinct').distinct(field, cond);
143
+ Model.exists = (cond) => mk('findOne', cond).select('_id').lean().transform((r) => (r ? { _id: r._id } : null));
144
+ Model.findOneAndUpdate = (cond, update, opts) => upd('findOneAndUpdate', cond, update, opts);
145
+ Model.findByIdAndUpdate = (id, update, opts) => upd('findOneAndUpdate', { _id: id }, update, opts);
146
+ Model.findOneAndReplace = (cond, repl, opts) => upd('findOneAndReplace', cond, repl, opts);
147
+ Model.findOneAndDelete = (cond, opts) => mk('findOneAndDelete', cond, null, opts);
148
+ Model.findByIdAndDelete = (id, opts) => mk('findOneAndDelete', { _id: id }, null, opts);
149
+ Model.findOneAndRemove = (cond, opts) => mk('findOneAndRemove', cond, null, opts);
150
+ Model.findByIdAndRemove = (id, opts) => mk('findOneAndRemove', { _id: id }, null, opts);
151
+ Model.updateOne = (cond, update, opts) => upd('updateOne', cond, update, opts);
152
+ Model.updateMany = (cond, update, opts) => upd('updateMany', cond, update, opts);
153
+ Model.update = (cond, update, opts) => upd('updateMany', cond, update, opts);
154
+ Model.replaceOne = (cond, repl, opts) => upd('replaceOne', cond, repl, opts);
155
+ Model.deleteOne = (cond, opts) => mk('deleteOne', cond, null, opts);
156
+ Model.deleteMany = (cond, opts) => mk('deleteMany', cond, null, opts);
157
+ Model.remove = (cond, opts) => mk('deleteMany', cond, null, opts);
158
+ Model.aggregate = (pipeline) => new Aggregate(Model, Array.isArray(pipeline) ? pipeline : pipeline ? [pipeline] : []);
159
+
160
+ // ---------- writes ----------
161
+ Model.create = async (docs, ...rest) => {
162
+ let options = {};
163
+ let list;
164
+ const single = !Array.isArray(docs) && rest.length === 0;
165
+ if (Array.isArray(docs)) { list = docs; if (rest[0] && isObj(rest[0])) options = rest[0]; } else list = [docs, ...rest];
166
+ const out = [];
167
+ for (const d of list) {
168
+ const doc = d && d.$isblackholeDocument && d.$__.model === Model ? d : new Model(d);
169
+ await doc.save(options);
170
+ out.push(doc);
171
+ }
172
+ return single ? out[0] : out;
173
+ };
174
+
175
+ const validationError = (doc, e) => {
176
+ const err = new ValidationError(doc);
177
+ for (const [p, x] of Object.entries(e)) err.addError(p, x);
178
+ err.message = `${name} validation failed: ${Object.values(e).map((x) => `${x.path}: ${x.message}`).join(', ')}`;
179
+ return err;
180
+ };
181
+
182
+ Model.insertMany = async (docs, options = {}) => {
183
+ const list = Array.isArray(docs) ? docs : [docs];
184
+ const prepared = [];
185
+ const errors = [];
186
+ for (const d of list) {
187
+ const doc = d && d.$isblackholeDocument ? d : new Model(d);
188
+ try {
189
+ await runHooks(schema, 'pre', 'validate', doc);
190
+ const e = await S.validateDocument(schema, doc._doc, doc);
191
+ if (Object.keys(e).length) throw validationError(doc, e);
192
+ prepared.push(doc);
193
+ } catch (err) { if (options.ordered === false) errors.push(err); else throw err; }
194
+ }
195
+ const inserted = [];
196
+ for (const doc of prepared) {
197
+ try { await runHooks(schema, 'pre', 'save', doc); Model.$persist(doc, options); await runHooks(schema, 'post', 'save', doc, [doc]); inserted.push(doc); }
198
+ catch (err) { if (options.ordered === false) errors.push(err); else throw err; }
199
+ }
200
+ if (options.rawResult) return { acknowledged: true, insertedCount: inserted.length, insertedIds: Object.fromEntries(inserted.map((d, i) => [i, d._id])), blackhole: { validationErrors: errors, results: inserted } };
201
+ if (errors.length && options.throwOnValidationError) throw errors[0];
202
+ if (options.lean) return inserted.map((d) => d.toObject());
203
+ return Array.isArray(docs) ? inserted : inserted[0];
204
+ };
205
+
206
+ Model.bulkWrite = async (ops, options = {}) => {
207
+ const res = { ok: 1, insertedCount: 0, matchedCount: 0, modifiedCount: 0, deletedCount: 0, upsertedCount: 0, insertedIds: {}, upsertedIds: {}, acknowledged: true };
208
+ let i = 0;
209
+ const addUpdate = (r) => { res.matchedCount += r.matchedCount; res.modifiedCount += r.modifiedCount; res.upsertedCount += r.upsertedCount; if (r.upsertedId) res.upsertedIds[i] = r.upsertedId; };
210
+ for (const op of ops) {
211
+ try {
212
+ if (op.insertOne) { const d = new Model(op.insertOne.document); await d.save(); res.insertedCount++; res.insertedIds[i] = d._id; }
213
+ else if (op.updateOne) addUpdate(await Model.updateOne(op.updateOne.filter, op.updateOne.update, { upsert: op.updateOne.upsert, arrayFilters: op.updateOne.arrayFilters }));
214
+ else if (op.updateMany) addUpdate(await Model.updateMany(op.updateMany.filter, op.updateMany.update, { upsert: op.updateMany.upsert, arrayFilters: op.updateMany.arrayFilters }));
215
+ else if (op.replaceOne) addUpdate(await Model.replaceOne(op.replaceOne.filter, op.replaceOne.replacement, { upsert: op.replaceOne.upsert }));
216
+ else if (op.deleteOne) res.deletedCount += (await Model.deleteOne(op.deleteOne.filter)).deletedCount;
217
+ else if (op.deleteMany) res.deletedCount += (await Model.deleteMany(op.deleteMany.filter)).deletedCount;
218
+ else throw new Error(`Unknown bulkWrite operation: ${Object.keys(op)[0]}`);
219
+ } catch (e) { if (options.ordered === false) (res.writeErrors = res.writeErrors || []).push(e); else throw e; }
220
+ i++;
221
+ }
222
+ res.isOk = () => true;
223
+ res.getWriteErrors = () => res.writeErrors || [];
224
+ return res;
225
+ };
226
+
227
+ // ---------- populate / misc ----------
228
+ Model.populate = async (docs, options) => {
229
+ const list = normalizePopulate([options]);
230
+ const arr = Array.isArray(docs) ? docs : [docs];
231
+ const lean = arr.length > 0 && arr[0] && !arr[0].$isblackholeDocument;
232
+ await populateResults(Model, arr, list, lean);
233
+ return docs;
234
+ };
235
+ Model.validate = async (obj, paths) => {
236
+ const casted = S.castDocument(schema, obj);
237
+ const errors = await S.validateDocument(schema, casted, casted, paths ? new Set(paths) : undefined);
238
+ if (Object.keys(errors).length) throw validationError({ $__name: name }, errors);
239
+ return casted;
240
+ };
241
+ Model.castObject = (obj) => S.castDocument(schema, obj);
242
+ Model.init = () => Promise.resolve(Model);
243
+ Model.createCollection = () => Promise.resolve(Model.collection);
244
+ Model.createIndexes = () => Promise.resolve();
245
+ Model.ensureIndexes = () => Promise.resolve();
246
+ Model.syncIndexes = () => Promise.resolve([]);
247
+ Model.cleanIndexes = () => Promise.resolve([]);
248
+ Model.listIndexes = () => Promise.resolve([{ v: 2, key: { _id: 1 }, name: '_id_' }, ...schema.indexes().map(([k, o]) => ({ v: 2, key: k, name: `${Object.keys(k).join('_')}_1`, ...o }))]);
249
+ Model.diffIndexes = () => Promise.resolve({ toDrop: [], toCreate: [] });
250
+ Model.startSession = () => db.startSession();
251
+ Model.watch = () => { throw new Error('Change streams are not supported by blackhole.db'); };
252
+ Model.discriminator = () => { throw new Error('Discriminators are not supported by blackhole.db'); };
253
+ Model.translateAliases = (o) => o;
254
+ Model.flush = () => col.flush();
255
+ Model.prototype.$model = Model;
256
+
257
+ return Model;
258
+ }
259
+
260
+ module.exports = { buildModel, Aggregate };
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "name": "blackhole.db",
3
- "version": "2.0.2",
3
+ "version": "3.0.1",
4
4
  "main": "index.js"
5
5
  }