liwi-mongo 8.3.1 → 9.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.
@@ -1,660 +0,0 @@
1
- import mongodb from 'mongodb';
2
- import { AbstractStoreCursor, AbstractConnection } from 'liwi-store';
3
- import { AbstractSubscribableStoreQuery, SubscribeStore } from 'liwi-subscribe-store';
4
- import mingo from 'mingo';
5
- import Logger from 'nightingale-logger';
6
-
7
- class MongoCursor extends AbstractStoreCursor {
8
- // key in AbstractCursor
9
- constructor(store, cursor) {
10
- super(store);
11
- this.cursor = cursor;
12
- }
13
-
14
- advance(count) {
15
- this.cursor.skip(count);
16
- }
17
-
18
- next() {
19
- return this.cursor.next().then(value => {
20
- this._result = value;
21
- this.key = value === null || value === void 0 ? void 0 : value._id;
22
- return this.key;
23
- });
24
- }
25
-
26
- limit(newLimit) {
27
- this.cursor.limit(newLimit);
28
- return Promise.resolve(this);
29
- }
30
-
31
- count(applySkipLimit = false) {
32
- return this.cursor.count(applySkipLimit);
33
- }
34
-
35
- result() {
36
- if (!this._result) throw new Error('Cannot call result() before next()');
37
- return Promise.resolve(this._result);
38
- }
39
-
40
- close() {
41
- if (this.cursor) {
42
- this.cursor.close();
43
- }
44
-
45
- return Promise.resolve();
46
- }
47
-
48
- toArray() {
49
- return this.cursor.toArray();
50
- }
51
-
52
- }
53
-
54
- /* eslint-disable complexity, max-lines */
55
-
56
- const identityTransformer$1 = model => model;
57
-
58
- class MongoQueryCollection extends AbstractSubscribableStoreQuery {
59
- constructor(store, options, transformer = identityTransformer$1) {
60
- super();
61
- this.store = store;
62
- this.options = options;
63
- this.transformer = transformer;
64
- }
65
-
66
- createTestCriteria() {
67
- if (!this.testCriteria) {
68
- if (!this.options.criteria) {
69
- return () => true;
70
- }
71
-
72
- const mingoQuery = new mingo.Query(this.options.criteria);
73
- this.testCriteria = mingoQuery.test.bind(mingoQuery);
74
- }
75
-
76
- return this.testCriteria;
77
- }
78
-
79
- async fetch(onFulfilled) {
80
- const cursor = await this.createMongoCursor();
81
- const [result, count] = await Promise.all([cursor.toArray(), cursor.count()]);
82
- return onFulfilled({
83
- result: result.map(this.transformer),
84
- meta: {
85
- total: count
86
- },
87
- info: {
88
- sort: this.options.sort,
89
- limit: this.options.limit,
90
- keyPath: this.store.keyPath
91
- }
92
- });
93
- }
94
-
95
- _subscribe(callback, _includeInitial) {
96
- const store = super.getSubscribeStore();
97
- const testCriteria = this.createTestCriteria();
98
- const promise = _includeInitial ? this.fetch(({
99
- result,
100
- meta,
101
- info
102
- }) => {
103
- callback(null, [{
104
- type: 'initial',
105
- initial: result,
106
- queryInfo: info,
107
- meta
108
- }]);
109
- }) : Promise.resolve();
110
- const unsubscribe = store.subscribe(action => {
111
- const changes = [];
112
-
113
- switch (action.type) {
114
- case 'inserted':
115
- {
116
- const filtered = action.next.filter(testCriteria);
117
-
118
- if (filtered.length > 0) {
119
- changes.push({
120
- type: 'inserted',
121
- result: filtered.map(this.transformer)
122
- });
123
- }
124
-
125
- break;
126
- }
127
-
128
- case 'deleted':
129
- {
130
- const filtered = action.prev.filter(testCriteria);
131
-
132
- if (filtered.length > 0) {
133
- changes.push({
134
- type: 'deleted',
135
- keys: filtered.map(object => object[this.store.keyPath])
136
- });
137
- }
138
-
139
- break;
140
- }
141
-
142
- case 'updated':
143
- {
144
- const {
145
- deleted,
146
- updated,
147
- inserted
148
- } = action.changes.reduce((acc, [prevObject, nextObject]) => {
149
- if (testCriteria(prevObject)) {
150
- if (!testCriteria(nextObject)) {
151
- acc.deleted.push(prevObject[this.store.keyPath]);
152
- } else {
153
- acc.updated.push(this.transformer(nextObject));
154
- }
155
- } else if (testCriteria(nextObject)) {
156
- acc.inserted.push(this.transformer(nextObject));
157
- }
158
-
159
- return acc;
160
- }, {
161
- deleted: [],
162
- updated: [],
163
- inserted: []
164
- });
165
-
166
- if (deleted.length > 0) {
167
- changes.push({
168
- type: 'deleted',
169
- keys: deleted
170
- });
171
- }
172
-
173
- if (updated.length > 0) {
174
- changes.push({
175
- type: 'updated',
176
- result: updated
177
- });
178
- }
179
-
180
- if (inserted.length > 0) {
181
- changes.push({
182
- type: 'inserted',
183
- result: inserted
184
- });
185
- }
186
-
187
- break;
188
- }
189
-
190
- default:
191
- throw new Error('Unsupported type');
192
- }
193
-
194
- if (changes.length === 0) return;
195
- callback(null, changes);
196
- }); // let _feed;
197
- // const promise = this.queryCallback(this.store.query(), this.store.r)
198
- // .changes({
199
- // includeInitial: _includeInitial,
200
- // includeStates: true,
201
- // includeTypes: true,
202
- // includeOffsets: true,
203
- // })
204
- // .then((feed) => {
205
- // if (args.length === 0) {
206
- // _feed = feed;
207
- // delete this._promise;
208
- // }
209
- //
210
- // feed.each(callback);
211
- // return feed;
212
- // });
213
- //
214
- // if (args.length === 0) this._promise = promise;
215
-
216
- return {
217
- stop: unsubscribe,
218
- cancel: unsubscribe,
219
- then: (onFulfilled, onRejected) => promise.then(onFulfilled, onRejected)
220
- };
221
- }
222
-
223
- async createMongoCursor() {
224
- const cursor = await this.store.cursor(this.options.criteria, this.options.sort);
225
-
226
- if (this.options.skip) {
227
- cursor.advance(this.options.skip);
228
- }
229
-
230
- if (this.options.limit) {
231
- await cursor.limit(this.options.limit);
232
- }
233
-
234
- return cursor;
235
- }
236
-
237
- }
238
-
239
- const identityTransformer = model => model;
240
-
241
- class MongoQuerySingleItem extends AbstractSubscribableStoreQuery {
242
- constructor(store, options, transformer = identityTransformer) {
243
- super();
244
- this.store = store;
245
- this.options = options;
246
- this.transformer = transformer;
247
- }
248
-
249
- createMingoTestCriteria() {
250
- if (!this.testCriteria) {
251
- if (!this.options.criteria) {
252
- return () => true;
253
- }
254
-
255
- const mingoQuery = new mingo.Query(this.options.criteria);
256
- this.testCriteria = mingoQuery.test.bind(mingoQuery);
257
- }
258
-
259
- return this.testCriteria;
260
- }
261
-
262
- async fetch(onFulfilled) {
263
- const cursor = await this.createMongoCursor();
264
- await cursor.limit(1);
265
- return cursor.toArray().then(result => {
266
- const item = result.length === 0 ? null : this.transformer(result[0]);
267
- return onFulfilled({
268
- result: item,
269
- meta: {
270
- total: result === null ? 0 : 1
271
- },
272
- info: {
273
- limit: 1,
274
- keyPath: this.store.keyPath
275
- }
276
- });
277
- });
278
- }
279
-
280
- _subscribe(callback, _includeInitial) {
281
- const store = super.getSubscribeStore();
282
- const testCriteria = this.createMingoTestCriteria();
283
- const promise = _includeInitial ? this.fetch(({
284
- result,
285
- meta,
286
- info
287
- }) => {
288
- callback(null, [{
289
- type: 'initial',
290
- initial: result,
291
- queryInfo: info,
292
- meta
293
- }]);
294
- }) : Promise.resolve();
295
- const unsubscribe = store.subscribe(async action => {
296
- const changes = [];
297
-
298
- switch (action.type) {
299
- case 'inserted':
300
- {
301
- const filtered = action.next.filter(testCriteria);
302
-
303
- if (filtered.length > 0) {
304
- changes.push({
305
- type: 'updated',
306
- result: this.transformer(filtered[0])
307
- });
308
- }
309
-
310
- break;
311
- }
312
-
313
- case 'deleted':
314
- {
315
- const filtered = action.prev.filter(testCriteria);
316
-
317
- if (filtered.length > 0) {
318
- changes.push({
319
- type: 'deleted',
320
- keys: filtered.map(object => object[this.store.keyPath])
321
- });
322
- }
323
-
324
- break;
325
- }
326
-
327
- case 'updated':
328
- {
329
- const filtered = action.changes.filter(([prev, next]) => testCriteria(prev));
330
-
331
- if (filtered.length > 0) {
332
- if (this.options.sort) {
333
- const {
334
- result
335
- } = await this.fetch(res => res);
336
- changes.push({
337
- type: 'updated',
338
- result
339
- });
340
- } else if (filtered.length !== 1) {
341
- throw new Error('should not match more than 1, use sort if you can have multiple match');
342
- } else {
343
- const [, next] = filtered[0];
344
- changes.push({
345
- type: 'updated',
346
- result: testCriteria(next) ? this.transformer(next) : null
347
- });
348
- }
349
- } else if (filtered.length === 0) ;
350
-
351
- break;
352
- }
353
-
354
- default:
355
- throw new Error('Unsupported type');
356
- }
357
-
358
- if (changes.length === 0) return;
359
- callback(null, changes);
360
- });
361
- return {
362
- stop: unsubscribe,
363
- cancel: unsubscribe,
364
- then: (onFulfilled, onRejected) => promise.then(onFulfilled, onRejected)
365
- };
366
- }
367
-
368
- async createMongoCursor() {
369
- const cursor = await this.store.cursor(this.options.criteria, this.options.sort);
370
-
371
- if (this.options.limit) {
372
- await cursor.limit(this.options.limit);
373
- }
374
-
375
- return cursor;
376
- }
377
-
378
- }
379
-
380
- /* eslint-disable max-lines */
381
- class MongoStore {
382
- constructor(connection, collectionName) {
383
- this.keyPath = '_id';
384
- this.connection = connection;
385
-
386
- if (!collectionName) {
387
- throw new Error(`Invalid collectionName: "${collectionName}"`);
388
- }
389
-
390
- this._collection = connection.getConnection().then(client => {
391
- this._collection = client.db().collection(collectionName);
392
- return this._collection;
393
- }, err => {
394
- this._collection = Promise.reject(err);
395
- return this._collection;
396
- });
397
- }
398
-
399
- get collection() {
400
- if (this.connection.connectionFailed) {
401
- return Promise.reject(new Error('MongoDB connection failed'));
402
- }
403
-
404
- return Promise.resolve(this._collection);
405
- }
406
-
407
- createQuerySingleItem(options, transformer) {
408
- return new MongoQuerySingleItem(this, options, transformer);
409
- }
410
-
411
- createQueryCollection(options, transformer) {
412
- return new MongoQueryCollection(this, options, transformer);
413
- }
414
-
415
- async insertOne(object) {
416
- if (!object._id) {
417
- object._id = new mongodb.ObjectID().toString();
418
- }
419
-
420
- if (!object.created) object.created = new Date();
421
- if (!object.updated) object.updated = new Date();
422
- const collection = await this.collection;
423
- const {
424
- result
425
- } = await collection.insertOne(object);
426
-
427
- if (!result.ok || result.n !== 1) {
428
- throw new Error('Fail to insert');
429
- }
430
-
431
- return object;
432
- }
433
-
434
- async replaceOne(object) {
435
- if (!object.updated) object.updated = new Date();
436
- const collection = await this.collection;
437
- await collection.replaceOne({
438
- _id: object._id
439
- }, object);
440
- return object;
441
- }
442
-
443
- async upsertOne(object, setOnInsertPartialObject) {
444
- const result = await this.upsertOneWithInfo(object, setOnInsertPartialObject);
445
- return result.object;
446
- }
447
-
448
- async upsertOneWithInfo(object, setOnInsertPartialObject) {
449
- const $setOnInsert = {
450
- created: object.created || new Date(),
451
- ...setOnInsertPartialObject
452
- };
453
-
454
- if (!object.updated) {
455
- object.updated = new Date();
456
- }
457
-
458
- const $set = { ...object
459
- };
460
- delete $set.created;
461
- const collection = await this.collection;
462
- const {
463
- upsertedCount
464
- } = await collection.updateOne({
465
- _id: object._id
466
- }, {
467
- $set,
468
- $setOnInsert
469
- }, {
470
- upsert: true
471
- });
472
-
473
- if (upsertedCount) {
474
- Object.assign(object, $setOnInsert);
475
- }
476
-
477
- return {
478
- object: object,
479
- inserted: !!upsertedCount
480
- };
481
- }
482
-
483
- replaceSeveral(objects) {
484
- return Promise.all(objects.map(object => this.replaceOne(object)));
485
- }
486
-
487
- async partialUpdateByKey(key, partialUpdate, criteria) {
488
- const collection = await this.collection;
489
- const commandResult = await collection.updateOne({
490
- _id: key,
491
- ...criteria
492
- }, partialUpdate);
493
-
494
- if (!commandResult.result.ok) {
495
- console.error(commandResult);
496
- throw new Error('Update failed');
497
- }
498
-
499
- const object = await this.findByKey(key);
500
- return object;
501
- }
502
-
503
- partialUpdateOne(object, partialUpdate) {
504
- return this.partialUpdateByKey(object._id, partialUpdate);
505
- }
506
-
507
- partialUpdateMany(criteria, partialUpdate) {
508
- return this.collection.then(collection => collection.updateMany(criteria, partialUpdate)).then(() => undefined); // TODO return updated object
509
- }
510
-
511
- deleteByKey(key, criteria) {
512
- return this.collection.then(collection => collection.deleteOne({
513
- _id: key,
514
- ...criteria
515
- })).then(() => undefined);
516
- }
517
-
518
- deleteOne(object) {
519
- return this.deleteByKey(object._id);
520
- }
521
-
522
- deleteMany(selector) {
523
- return this.collection.then(collection => collection.deleteMany(selector)).then(() => undefined);
524
- }
525
-
526
- cursor(criteria, sort) {
527
- return this.collection.then(collection => collection.find(criteria)).then(sort && (cursor => cursor.sort(sort))).then(cursor => new MongoCursor(this, cursor));
528
- }
529
-
530
- findByKey(key, criteria) {
531
- return this.collection.then(collection => collection.findOne({
532
- _id: key,
533
- ...criteria
534
- })).then(result => result || undefined);
535
- }
536
-
537
- findAll(criteria, sort) {
538
- return this.cursor(criteria, sort).then(cursor => cursor.toArray());
539
- }
540
-
541
- findOne(criteria, sort) {
542
- return this.collection.then(collection => collection.find(criteria)).then(sort && (cursor => cursor.sort(sort))).then(cursor => cursor.limit(1).next());
543
- }
544
-
545
- }
546
-
547
- const logger = new Logger('liwi:mongo:MongoConnection');
548
- class MongoConnection extends AbstractConnection {
549
- // TODO interface
550
- constructor(config) {
551
- super();
552
-
553
- if (!config.has('host')) {
554
- config.set('host', 'localhost');
555
- }
556
-
557
- if (!config.has('port')) {
558
- config.set('port', '27017');
559
- }
560
-
561
- if (!config.has('database')) {
562
- throw new Error('Missing config database');
563
- }
564
-
565
- const connectionString = `mongodb://${config.has('user') ? `${config.get('user')}:${config.get('password')}@` : ''}` + `${config.get('host')}:${config.get('port')}/${config.get('database')}`;
566
- this.connect(connectionString);
567
- }
568
-
569
- connect(connectionString) {
570
- logger.info('connecting', {
571
- connectionString
572
- });
573
- const connectPromise = mongodb.MongoClient.connect(connectionString, {
574
- useNewUrlParser: true
575
- }).then(connection => {
576
- logger.info('connected', {
577
- connectionString
578
- });
579
- connection.on('close', () => {
580
- logger.warn('close', {
581
- connectionString
582
- });
583
- this.connectionFailed = true;
584
-
585
- this.getConnection = () => {
586
- throw new Error('MongoDB connection closed');
587
- };
588
- });
589
- connection.on('timeout', () => {
590
- logger.warn('timeout', {
591
- connectionString
592
- });
593
- this.connectionFailed = true;
594
-
595
- this.getConnection = () => {
596
- throw new Error('MongoDB connection timeout');
597
- };
598
- });
599
- connection.on('reconnect', () => {
600
- logger.warn('reconnect', {
601
- connectionString
602
- });
603
- this.connectionFailed = false;
604
-
605
- this.getConnection = () => Promise.resolve(this._connection);
606
- });
607
- connection.on('error', err => {
608
- logger.warn('error', {
609
- connectionString,
610
- err
611
- });
612
- });
613
- this._connection = connection;
614
- this._connecting = undefined;
615
-
616
- this.getConnection = () => Promise.resolve(this._connection);
617
-
618
- return connection;
619
- }).catch(err => {
620
- logger.info('not connected', {
621
- connectionString
622
- });
623
- console.error(err.message || err); // throw err;
624
-
625
- process.nextTick(() => {
626
- // eslint-disable-next-line unicorn/no-process-exit
627
- process.exit(1);
628
- });
629
- throw err;
630
- });
631
-
632
- this.getConnection = () => Promise.resolve(connectPromise);
633
-
634
- this._connecting = this.getConnection();
635
- }
636
-
637
- getConnection() {
638
- throw new Error('call connect()');
639
- }
640
-
641
- async close() {
642
- this.getConnection = () => Promise.reject(new Error('Connection closed'));
643
-
644
- if (this._connection) {
645
- await this._connection.close();
646
- this._connection = undefined;
647
- } else if (this._connecting) {
648
- await this._connecting;
649
- await this.close();
650
- }
651
- }
652
-
653
- }
654
-
655
- function createMongoSubscribeStore(mongoStore) {
656
- return new SubscribeStore(mongoStore);
657
- }
658
-
659
- export { MongoConnection, MongoStore, createMongoSubscribeStore };
660
- //# sourceMappingURL=index-node12.mjs.map