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 | 2x
2x
2x
2x
2x
2x
2x
30x
1x
29x
1x
28x
28x
28x
28x
28x
28x
28x
10x
2x
2x
21x
21x
20x
1x
19x
78x
19x
19x
19x
19x
19x
19x
19x
19x
2x
2x
2x
2x
2x
2x
2x
2x
2x
2x
2x
2x
4x
1x
3x
3x
3x
1x
2x
2x
2x
8x
2x
2x
2x
2x
1x
1x
3x
3x
1x
1x
1x
1x
2x
2x
1x
6x
1x
1x
3x
1x
2x
2x
2x
1x
1x
1x
4x
1x
1x
1x
1x
4x
1x
3x
1x
2x
1x
48x
48x
1x
21x
9x
12x
12x
9x
3x
12x
12x
12x
12x
5x
7x
3x
3x
3x
1x
4x
3x
1x
2x
8x
7x
1x
14x
14x
14x
54x
2x
| const fs = require('fs');
const atomic = require('atomic-write');
const { PocketDB } = require('./pocketdb');
const _queryItems = Symbol('queryItems');
const _findWithOptions = Symbol('findWithOptions');
const _sortByKey = Symbol('sortByKey');
const _syncCollection = Symbol('syncCollection');
class Collection {
/**
* @param {Class} db A PocketDB instance.
* @param {String} collectionName The name of the collection.
*/
constructor(db, collectionName) {
// If the `db` arg is not a PocketDB instance, then throw an error
if (!(db instanceof PocketDB)) {
throw new TypeError('DB isn\'t a valid PocketDB instance.');
}
// If the db already has a collection with the same name, then throw an error
if (db.db[collectionName]) {
throw new Error('A collection with that name already exists.');
}
this.path = db.getCollectionPath(collectionName);
this.name = collectionName;
this.events = ['beforeSave', 'afterSave', 'beforeRemove', 'afterRemove'];
this.listeners = [];
// Set the collection to the data from disk if it exists, or default collection data
this._collection = db.getCollectionData(collectionName);
// And add the collection instance to the DB
db.loadCollection(this);
this[_syncCollection]();
}
/**
* Finds all items in a collection given a query.
*
* @param {Object|Function} query A query object or .filter() function.
* @param {Object} options A options object e.g. `{ sort: 'name' }`.
* @return {Promise} A list of found objects.
*/
find(query, options) {
return Promise.resolve(this[_findWithOptions](query, options));
}
/**
* Finds the first item in a collection given a query.
*
* @param {Object|Function} query A query object or .filter() function.
* @param {Object} options A options object e.g. `{ sort: 'name' }`.
* @return {Promise} The found object.
*/
findOne(query, options) {
return Promise.resolve(this[_findWithOptions](query, options)[0]);
}
/**
* Counts the number of items in a collection given a query.
*
* @param {Object|Function} query A query object or .filter() function.
* @param {Object} options A options object e.g. `{ sort: 'name' }`.
* @return {Promise} The total count of items in a collection.
*/
count(query, options) {
return Promise.resolve(this[_findWithOptions](query, options).length);
}
/**
* Method called before all insert operations.
* It allows you to change some data before it's inserted.
*
* @param {Object|Array} data The data to do things with.
* @return {Object|Array} The data that's been changed.
*/
preInsert(data) {
return data;
}
/**
* Method called after all insert operations.
* It gives you access to the object after it was saved to the collection.
*
* @param {Object|Array} data The data to do things with.
* @return {Object|Array}
*/
postSave(data) {
return data;
}
/**
* Insert multiple items into the DB.
*
* @param {Array} items A list of items to insert.
* @return {Array} The items that were inserted.
*/
insert(items) {
if (!Array.isArray(items)) {
return Promise.reject(new Error('You must pass a valid array to `.insert()`.'));
}
const id = this._collection.nextID;
const data = items.map((item, index) => Object.assign({}, { id: id + index }, item));
// Create a list of new items by calling the preInsert hook
// with the list of items to be inserted
const newItems = this.preInsert(data);
this.emit('beforeSave', { original: items, modified: newItems });
this._collection.items = this._collection.items.concat(newItems);
this._collection.nextID = id + items.length;
this.postSave(newItems);
this.emit('afterSave', { original: items, modified: newItems });
this[_syncCollection]();
return Promise.resolve(newItems);
}
/**
* Insert a single item into the DB.
*
* @param {Object} item An item to insert.
* @return {Object} The item that was inserted.
*/
insertOne(item) {
const id = this._collection.nextID;
const data = Object.assign({}, { id }, item);
// Create a new item by calling the preInsert hook with the new data
const newItem = this.preInsert(data);
this.emit('beforeSave', { original: item, modified: newItem });
this._collection.items = this._collection.items.concat(newItem);
this._collection.nextID++;
this.postSave(newItem);
this.emit('afterSave', { original: item, modified: newItem });
this[_syncCollection]();
return Promise.resolve(newItem);
}
/**
* Method called before all update operations.
* It allows you to change some data before it's inserted.
*
* @param {Object|Array} data The data to do things with.
* @return {Object|Array} The data that's been changed.
*/
preUpdate(data) {
return data;
}
/**
* Method called after all update operations.
* It gives you access to the object after it was saved to the collection.
*
* @param {Object|Array} data The data to do things with.
* @return {Object|Array}
*/
postUpdate(data) {
return data;
}
/**
* Updates a single item into the DB.
* The update isn't merged with the existing item, meaning the
* existing item will be overwritten with exception to the `id` key.
*
* @param {Object|Function} query A query object or .filter() function.
* @param {Object} data The new data to update with.
* @return {Object} The item that was updated.
*/
updateOne(query, data) {
if (!query) {
return Promise.reject(new Error('You must specify a query to update an item.'));
}
const items = this._collection.items;
const queryResult = this[_queryItems](query, items)[0];
// If it didn't find any items to update, then reject
if (!queryResult || !queryResult.id) {
return Promise.reject(new Error('Didn\'t find any items to update.'));
}
// Construct the new item to be saved
const withPreUpdate = this.preUpdate(data);
const updatedItem = Object.assign({}, withPreUpdate, { id: queryResult.id });
this.emit('beforeSave', { original: queryResult, modified: updatedItem });
// And save it to the collection by removing the existing item and appending the update
this._collection.items = items.filter(i => i.id !== queryResult.id).concat(updatedItem);
this.postUpdate(updatedItem);
this.emit('afterSave', { original: queryResult, modified: updatedItem });
this[_syncCollection]();
return Promise.resolve(updatedItem);
}
/**
* Method called before all remove operations.
* It gives you access to the object before it gets removed from the collection.
*
* @param {Object|Array} data The data to do things with.
* @return {Object|Array}
*/
preRemove(data) {
return data;
}
/**
* Method called after all remove operations.
* It gives you access to the object after it was removed from the collection.
*
* @param {Object|Array} data The data to do things with.
* @return {Object|Array}
*/
postRemove(data) {
return data;
}
/**
* Removes a list of items that match a given query from the DB.
* If no query is provided, then all items are removed and the counter is reset.
*
* @param {Object|Function} query A query object or .filter() function.
* @return {Promise} The items that were removed.
*/
remove(query) {
const items = this._collection.items;
if (!query) {
this._collection.items = [];
this._collection.nextID = 1;
this[_syncCollection]();
return Promise.resolve(items);
}
const queryResult = this[_queryItems](query, items);
if (!queryResult || !queryResult.length) {
return Promise.reject(new Error('Didn\'t find any items to remove.'));
}
this._collection.items = items.filter(i => !queryResult.includes(i));
this[_syncCollection]();
return Promise.resolve(queryResult);
}
/**
* Removes a single item from the DB.
*
* @param {Object|Function} query A query object or .filter() function.
* @return {Object} The item that was updated.
*/
removeOne(query) {
if (!query) {
return Promise.reject(new Error('You must specify a query to remove an item.'));
}
const items = this._collection.items;
const queryResult = this[_queryItems](query, items)[0];
if (!queryResult || !queryResult.id) {
return Promise.reject(new Error('Didn\'t find any items to remove.'));
}
this.preRemove(queryResult);
this.emit('beforeRemove', { original: queryResult, modified: queryResult });
this._collection.items = items.filter(i => i.id !== queryResult.id);
this.postRemove(queryResult);
this.emit('afterRemove', { original: queryResult, modified: queryResult });
this[_syncCollection]();
return Promise.resolve(queryResult);
}
/**
* Adds a listener to the collection so other things can observe certain events.
*
* @param {String} eventName The naem of the event to listen for.
* @param {Function} listener A listener function to be called when events are emitted.
* @param {String} id A unique identifier for a listener. Used by `removeListener(id)`.
*/
addListener(eventName, listener, id) {
if (!this.events.includes(eventName)) {
throw new Error(
`${eventName} is not a valid event name. Event names are: ${this.events.join(', ')}`
);
}
if (this.listeners.find(l => (l.id === id && l.eventName === eventName))) {
throw new Error(`A listener for "${eventName}" with id "${id}" already exists.`);
}
this.listeners.push({
eventName,
listener,
id
});
}
/**
* Removes a listener from the collection.
*
* @param {String} id The ID of the listener to remove.
*/
removeListener(id) {
this.listeners = this.listeners.filter(l => l.id !== id);
}
/**
* Calls each listener function for a given event with some data.
*
* @param {String} eventName The event to listen for.
* @param {Array} args Any args that should be passed to the listener.
*/
emit(eventName, data) {
const listeners = this.listeners.filter(l => l.eventName === eventName);
for (const listener of listeners) {
listener.listener(data);
}
}
/**
* Searches a list of items for a given query and returns a copy of the result.
*
* @param {Object|Function} query A query object or .filter() function.
* @param {Array} items The list of items to search within.
* @return {Array} The results of the query.
*/
[_queryItems](query, items) {
// If the query arg is a filter function, then apply it and return the result
if (query.constructor && query.call && query.apply) {
return items.filter(query);
}
const queryKeys = Object.keys(query);
// If the query is an empty object, just return a copy of the un filtered items
if (queryKeys.length === 0) {
return [...items];
}
// Search for and return the items that match the query object
return items.filter(item => {
let matches = 0;
// Check if any of the key/values in the query match any the items key/values
for (const key of queryKeys) {
if (item[key] && item[key] === query[key]) matches++;
}
// If the item matched on all the query key/values the return it
if (queryKeys.length === matches) {
return true;
}
return false;
});
}
/**
* .sort() function that sorts items by a given key.
*
* @param {String} key The key to sort by.
* @return {Function} A function that .sort() will accept.
*/
[_sortByKey](key) {
const reverse = key.startsWith('-');
const k = reverse ? key.replace('-', '') : key;
if (reverse) {
return (a, b) => {
if (a[k] < b[k]) return 1;
if (a[k] > b[k]) return -1;
return 0;
};
}
return (a, b) => {
if (a[k] < b[k]) return -1;
if (a[k] > b[k]) return 1;
return 0;
};
}
/**
* Finds items in the collection that match a query and optionally sorts them.
*
* @param {Object|Function} query A query object or .filter() function.
* @param {Object} options A options object e.g. `{ sort: 'name' }`.
* @return {Array} The list of found items, optionally sorted.
*/
[_findWithOptions](query = {}, options = {}) {
const sortKey = options.sort ? options.sort : null;
const newItems = this[_queryItems](query, this._collection.items);
return sortKey ? newItems.sort(this[_sortByKey](sortKey)) : newItems;
}
/**
* Saves the current collection state to disk.
*/
[_syncCollection]() {
atomic.writeFile(this.path, JSON.stringify(this._collection), () => {});
}
}
module.exports = {
Collection
};
|