blackhole.db 1.1.1 → 2.0.0

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.
Files changed (3) hide show
  1. package/index.js +50 -52
  2. package/index.node +0 -0
  3. package/package.json +2 -5
package/index.js CHANGED
@@ -1,11 +1,7 @@
1
1
  const native = require('./index.node');
2
- const { v4: uuidv4 } = require('uuid');
3
2
 
4
3
  const _internal = new WeakMap();
5
4
 
6
- /**
7
- * 1. GLOBAL BLACKHOLE FUNCTIONS
8
- */
9
5
  const blackhole = {
10
6
  models: {},
11
7
  connect: async (path = 'blackhole.db') => {
@@ -13,7 +9,7 @@ const blackhole = {
13
9
  return blackhole.connection;
14
10
  },
15
11
  createConnection: (path) => blackhole.connect(path),
16
- disconnect: async () => {},
12
+ disconnect: async () => {},
17
13
  model: (name, schema) => {
18
14
  if (!schema) return blackhole.models[name];
19
15
  return blackhole.models[name] = new Model(name, schema);
@@ -40,36 +36,47 @@ const blackhole = {
40
36
  };
41
37
  }
42
38
  },
43
- Types: { ObjectId: () => uuidv4() },
39
+ Types: { ObjectId: (v) => (v != null ? String(v) : undefined) },
44
40
  connection: { on: () => {}, once: () => {} },
45
41
  set: () => {},
46
42
  pluralize: (v) => v
47
43
  };
48
44
 
49
- /**
50
- * 5. QUERY HELPERS (Chainable)
51
- */
45
+ function normalizeProjection(p) {
46
+ if (!p) return null;
47
+ if (typeof p === 'string') {
48
+ const obj = {};
49
+ for (const f of p.split(/\s+/).filter(Boolean)) {
50
+ if (f.startsWith('-')) obj[f.slice(1)] = 0;
51
+ else obj[f] = 1;
52
+ }
53
+ return obj;
54
+ }
55
+ return p;
56
+ }
57
+
52
58
  class Query {
53
- constructor(model, filter, op) {
54
- this.model = model; this._filter = filter || {}; this._op = op;
55
- this._limit = 0; this._skip = 0; this._sort = null; this._isLean = false;
59
+ constructor(model, filter, op, projection) {
60
+ this.model = model; this._filter = filter; this._op = op;
61
+ this._limit = -1; this._skip = -1; this._sort = null; this._isLean = false;
62
+ this._projection = normalizeProjection(projection);
56
63
  }
64
+ select(p) { this._projection = normalizeProjection(p); return this; }
57
65
  limit(n) { this._limit = n; return this; }
58
66
  skip(n) { this._skip = n; return this; }
59
67
  sort(s) { this._sort = s; return this; }
60
68
  lean(v = true) { this._isLean = v; return this; }
61
69
 
62
70
  async exec() {
63
- let raw = JSON.parse(native.scan(this.model._prefix, JSON.stringify(this._filter)));
64
-
65
- if (this._sort) {
66
- const k = Object.keys(this._sort)[0], d = this._sort[k];
67
- raw.sort((a, b) => a[k] > b[k] ? d : -d);
68
- }
69
-
70
- if (this._skip || this._limit) {
71
- raw = raw.slice(this._skip, this._limit ? this._skip + this._limit : undefined);
72
- }
71
+ const filter = this._op === 'findById' ? { _id: this._filter } : (this._filter || {});
72
+ const raw = JSON.parse(native.find(
73
+ this.model._collection,
74
+ JSON.stringify(filter),
75
+ JSON.stringify(this._projection || {}),
76
+ JSON.stringify(this._sort || {}),
77
+ this._skip,
78
+ this._limit,
79
+ ));
73
80
 
74
81
  if (this._op === 'findOne' || this._op === 'findById') {
75
82
  const res = raw[0] || null;
@@ -79,31 +86,26 @@ class Query {
79
86
  return this._isLean ? raw : raw.map(r => this.model._wrap(r));
80
87
  }
81
88
  then(res, rej) { return this.exec().then(res, rej); }
89
+ catch(rej) { return this.exec().catch(rej); }
82
90
  }
83
91
 
84
- /**
85
- * 4. DOCUMENT FUNCTIONS (Instance)
86
- */
87
92
  class Document {
88
93
  constructor(data, model) {
89
- const id = data._id || data._key?.split('/')[1] || uuidv4();
90
- const key = data._key || model._keyFor(id);
94
+ const id = data._id != null ? String(data._id) : null;
91
95
 
92
- // Create Proxy first to avoid state binding issues
93
96
  const proxy = new Proxy(this, {
94
97
  set: (t, p, v) => {
95
98
  const state = _internal.get(proxy);
96
- if (p === 'id' || p === '_id') return true; // Read-only getters
99
+ if (p === 'id' || p === '_id') return true;
97
100
  if (state) state.modified.add(p);
98
101
  t[p] = v; return true;
99
102
  }
100
103
  });
101
104
 
102
- _internal.set(proxy, { model, id, key, modified: new Set(), isNew: !data._key });
105
+ _internal.set(proxy, { model, id, modified: new Set(), isNew: id == null });
103
106
 
104
- // Initialize values into proxy (filtering out getters)
105
107
  for (let [k, v] of Object.entries(data)) {
106
- if (k !== '_id' && k !== 'id' && k !== '_key') proxy[k] = v;
108
+ if (k !== '_id' && k !== 'id') proxy[k] = v;
107
109
  }
108
110
 
109
111
  for (let [n, f] of Object.entries(model.schema.methods)) this[n] = f.bind(proxy);
@@ -117,15 +119,19 @@ class Document {
117
119
  const state = _internal.get(this);
118
120
  await state.model._runHooks('pre', 'save', this);
119
121
  const data = this.toObject();
120
- data._id = state.id;
121
- native.put(state.key, JSON.stringify(data));
122
+ const id = native.save(state.model._collection, state.id || '', JSON.stringify(data));
123
+ state.id = id;
124
+ state.isNew = false;
122
125
  state.modified.clear();
123
126
  await state.model._runHooks('post', 'save', this);
124
127
  return this;
125
128
  }
126
129
 
127
130
  async updateOne(u) { Object.assign(this, u); return this.save(); }
128
- async deleteOne() { return native.del(_internal.get(this).key); }
131
+ async deleteOne() {
132
+ const state = _internal.get(this);
133
+ return native.delete_by_id(state.model._collection, state.id);
134
+ }
129
135
  isModified(p) { return _internal.get(this).modified.has(p); }
130
136
  markModified(p) { _internal.get(this).modified.add(p); }
131
137
  validate() { return true; }
@@ -146,20 +152,14 @@ class Document {
146
152
  return o;
147
153
  }
148
154
  }
149
-
150
- /**
151
- * 3. MODEL FUNCTIONS (Statics)
152
- */
153
155
  class Model {
154
156
  constructor(name, schema) {
155
- this.name = name; this.schema = schema; this._prefix = `${name}/`;
157
+ this.name = name; this.schema = schema; this._collection = name;
156
158
  Object.assign(this, schema.statics);
157
159
  }
158
- _keyFor(id) { return `${this._prefix}${id}`; }
159
160
  _wrap(raw) { return new Document(raw, this); }
160
161
  async _runHooks(p, e, d) { for (let f of this.schema._hooks[p][e] ?? []) await f.call(d); }
161
162
 
162
- // Create
163
163
  async create(data) {
164
164
  if (Array.isArray(data)) return Promise.all(data.map(d => this.create(d)));
165
165
  const doc = new Document(data, this);
@@ -167,17 +167,14 @@ class Model {
167
167
  }
168
168
  async insertMany(arr) { return this.create(arr); }
169
169
 
170
- // Read
171
- find(f) { return new Query(this, f, 'find'); }
172
- findOne(f) { return new Query(this, f, 'findOne'); }
173
- findById(id) { return this.findOne({ _id: id }); }
174
- async countDocuments(f) { return (await this.find(f)).length; }
170
+ find(f, projection) { return new Query(this, f, 'find', projection); }
171
+ findOne(f, projection) { return new Query(this, f, 'findOne', projection); }
172
+ findById(id, projection) { return new Query(this, id, 'findById', projection); }
173
+ async countDocuments(f) { return native.count(this._collection, JSON.stringify(f || {})); }
175
174
  async distinct(field) {
176
175
  const all = await this.find({}).lean();
177
176
  return [...new Set(all.map(x => x[field]))];
178
177
  }
179
-
180
- // Update
181
178
  async updateOne(f, u) {
182
179
  const d = await this.findOne(f).exec();
183
180
  if (!d) return { matchedCount: 0 };
@@ -196,7 +193,6 @@ class Model {
196
193
  }
197
194
  findByIdAndUpdate(id, u, o) { return this.findOneAndUpdate({ _id: id }, u, o); }
198
195
 
199
- // Delete
200
196
  async deleteOne(f) {
201
197
  const d = await this.findOne(f).exec();
202
198
  if (!d) return { deletedCount: 0 };
@@ -213,8 +209,10 @@ class Model {
213
209
  }
214
210
  findByIdAndDelete(id) { return this.findOneAndDelete({ _id: id }); }
215
211
 
216
- // Advanced
217
- async aggregate(p) { return this.find({}).lean(); }
212
+ async aggregate(pipeline) {
213
+ const raw = native.aggregate(this._collection, JSON.stringify(pipeline || []));
214
+ return JSON.parse(raw);
215
+ }
218
216
  async bulkWrite(ops) {
219
217
  for (let o of ops) {
220
218
  if (o.insertOne) await this.create(o.insertOne.document);
package/index.node CHANGED
Binary file
package/package.json CHANGED
@@ -1,8 +1,5 @@
1
1
  {
2
2
  "name": "blackhole.db",
3
- "version": "1.1.1",
4
- "main": "index.js",
5
- "dependencies": {
6
- "uuid": "^9.0.1"
7
- }
3
+ "version": "2.0.0",
4
+ "main": "index.js"
8
5
  }