This repository has been archived by the owner on Feb 10, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 103
/
mongorito.js
781 lines (589 loc) · 13.9 KB
/
mongorito.js
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
/**
* Dependencies
*/
const ObjectID = require('monk/node_modules/mongoskin').ObjectID;
const mongoskin = require('monk/node_modules/mongoskin');
const pluralize = require('pluralize');
const compose = require('koa-compose');
const result = require('lodash.result');
const monk = require('monk');
const wrap = require('co-monk');
const is = require('is_js');
const Query = require('./query');
const util = require('./util');
/**
* Mongorito
*
* Main class, manages mongodb connection and collections
*/
class Mongorito {
/**
* Connect to a MongoDB database and return connection object
*
* @param {String} urls - connection urls (as arguments)
* @api public
*/
static connect (...urls) {
// convert mongo:// urls to monk-supported ones
urls = urls.map(url => url.replace(/^mongo\:\/\//, ''));
let db = monk(...urls);
// if there is already a connection
// don't overwrite it with a new one
if (!this.db) this.db = db;
return db;
}
/**
* Disconnect from a database
*
* @api public
*/
static disconnect () {
this.db.close();
}
/**
* Alias for .disconnect()
*
* @api public
*/
static close () {
return this.disconnect(...arguments);
}
/**
* Return a co-wrapped monk collection
*
* @api private
*/
static _collection (db, name) {
let url = db.driver._connect_args[0];
let collections = this._collections[url];
if (!collections) {
collections = this._collections[url] = {};
}
if (collections[name]) return collections[name];
let collection = db.get(name);
collections[name] = wrap(collection);
return collections[name];
}
}
/**
* Cache for monk collections
*
* @api private
*/
Mongorito._collections = {};
/**
* Model
*/
class Model {
constructor (attrs = {}, options = {}) {
this.attributes = attrs;
this.changed = {};
this.previous = {};
this.options = options;
// reset hooks
Object.defineProperty(this, '_hooks', {
value: {
before: {
create: [],
update: [],
remove: [],
save: []
},
after: {
create: [],
update: [],
remove: [],
save: []
}
},
enumerable: false
});
// run custom per-model configuration
this.configure();
}
/**
* Get collection for current model
*
* @api private
*/
get _collection () {
if (is.string(this.collection)) {
return Mongorito._collection(this._db, this.collection);
}
// get collectio name
// from the "collection" property
// or generate the default one
let defaultName = pluralize(this.constructor.name).toLowerCase();
let name = result(this, 'collection', defaultName);
// save collection name
// to avoid the same check in future
this.collection = this.constructor.prototype.collection = name;
return Mongorito._collection(this._db, this.collection);
}
/**
* Get database for current model
*
* @api private
*/
get _db () {
// use either custom database
// specified for this model
// or use a default one
return this.db || Mongorito.db;
}
/**
* Get model attribute
*
* @param {String} key - property name
* @api public
*/
get (key) {
let attrs = this.attributes;
// if key is not set
// return all attributes
return key ? attrs[key] : attrs;
}
/**
* Set model attribute
*
* @param {String} key - property name
* @param {Mixed} value - property value
* @api public
*/
set (key, value) {
// if object passed instead of key-value pair
// iterate and call set on each item
if (is.object(key)) {
let attrs = key;
let keys = Object.keys(attrs);
keys.forEach(key => {
this.set(key, attrs[key]);
});
return;
}
// check if the value actually changed
if (this.get(key) !== value) {
this.previous[key] = this.get(key);
this.attributes[key] = value;
this.changed[key] = true;
}
return value;
}
/**
* Set default values
*
* @api private
*/
_setDefaults () {
let defaults = result(this, 'defaults', {});
let keys = Object.keys(defaults);
keys.forEach(key => {
let defaultValue = defaults[key];
let actualValue = this.get(key);
if (is.undefined(actualValue)) {
this.set(key, defaultValue);
}
});
}
/**
* Get all attributes
*
* @api public
*/
toJSON () {
return this.attributes;
}
/**
* Configure model (usually, set hooks here)
* Supposed to be overriden
*
* @api public
*/
configure () {
}
/**
* Rollback given method when error occurs
* Supposed to be overriden
*
* @param {String} name - method name
* @api public
*/
* rollback () {
}
/**
* Return a function, that in case of an error
* executes this.rollback() with a given method name
*
* @api private
*/
_rollbackFor (method) {
return function * (next) {
try {
yield* next;
} catch (err) {
yield this.rollback(method);
throw err;
}
}
}
/**
* Add hooks
*
* @api private
*/
hook (when, action, method) {
// if object is given
// iterate and call .hook()
// for each entry
if (is.object(when)) {
let hooks = when;
let keys = Object.keys(hooks);
keys.forEach(key => {
let [when, action] = key.split(':');
let method = hooks[key];
this.hook(when, action, method);
});
return;
}
// if array is given
// iterate and call .hook()
// for each item
if (is.array(method)) {
let methods = method;
methods.forEach(method => this.hook(when, action, method));
return;
}
// if method is a string
// get the function
if (is.not.function(method)) method = this[method];
// around hooks should be
// at the end of before:*
// at the beginning of after:*
if (when === 'around') {
this._hooks.before[action].push(method);
this._hooks.after[action].unshift(method);
} else {
this._hooks[when][action].push(method);
}
}
/**
* Add multiple hooks at once
*
* @api public
*/
hooks () {
return this.hook.apply(this, arguments);
}
/**
* Add before:* hook
*
* @param {String} action - before what
* @param {String} method - hook name
* @api public
*/
before (action, method) {
this.hook('before', action, method);
}
/**
* Add after:* hook
*
* @param {String} action - after what
* @param {String} method - hook name
* @api public
*/
after (action, method) {
this.hook('after', action, method);
}
/**
* Add around:* hook
*
* @param {String} action - around what
* @param {String} method - hook name
* @api public
*/
around (action, method) {
this.hook('around', action, method);
}
/**
* Execute hooks
*
* @api private
*/
_runHooks (when, action, options = {}) {
let hooks = this._getHooks(when, action);
// skip hooks
let skip = options.skip;
if (skip) {
if (is.string(skip)) skip = [skip];
hooks = hooks.filter(fn => skip.indexOf(fn.name) === -1);
}
let middleware = [];
// insert a rollback fn
// before each hook
hooks.forEach(fn => {
let rollback = this._rollbackFor(fn.name);
middleware.push(rollback, fn);
});
return compose(middleware).call(this);
}
/**
* Get hooks for a given operation
*
* @api private
*/
_getHooks (when, action) {
let hooks = this._hooks[when][action] || [];
// if create or update hooks requested
// prepend save hooks also
if (action === 'create' || action === 'update') {
hooks.push.apply(hooks, this._hooks[when]['save']);
}
return hooks;
}
/**
* Save a model
*
* @param {Object} options - options for save operation
* @api public
*/
* save (options) {
// set default values if needed
this._setDefaults();
let id = this.get('_id');
let fn = id ? this.update : this.create;
// revert populated documents to _id's
let populate = this.options.populate || emptyObject;
let keys = Object.keys(populate);
keys.forEach(key => {
let value = this.get(key);
if (is.array(value)) {
value = value.map(doc => doc.get('_id'));
} else {
value = value.get('_id');
}
this.set(key, value);
});
return yield fn.call(this, options);
}
/**
* Create a model
*
* @api private
*/
* create (options) {
let collection = this._collection;
let attrs = this.attributes;
let date = new Date;
this.set({
created_at: date,
updated_at: date
});
yield* this._runHooks('before', 'create', options);
let doc = yield collection.insert(attrs);
this.set('_id', doc._id);
yield* this._runHooks('after', 'create', options);
return this;
}
/**
* Update a model
*
* @api private
*/
* update (options) {
let collection = this._collection;
let attrs = this.attributes;
this.set('updated_at', new Date);
yield* this._runHooks('before', 'update', options);
yield collection.updateById(attrs._id, attrs);
yield* this._runHooks('after', 'update', options);
return this;
}
/**
* Remove a model
*
* @api private
*/
* remove (options) {
let collection = this._collection;
yield* this._runHooks('before', 'remove', options);
yield collection.remove({ _id: this.get('_id') });
yield* this._runHooks('after', 'remove', options);
return this;
}
/**
* Atomically increment a model property
*
* @param {Object} props - set of properties and values
* @param {Object} options - options for update operation
* @api public
*/
* inc (props, options) {
let id = this.get('_id');
if (!id) {
throw new Error('Can\'t atomically increment a property of unsaved document.');
}
let collection = this._collection;
yield* this._runHooks('before', 'update', options);
yield collection.updateById(id, {
'$inc': props
});
// perform increment locally
// to prevent the need to refresh
// the model from a database
Object.keys(props).forEach(key => {
// get current value
let value = this.get(key);
// perform increment
value += props[key];
// save
this.set(key, value);
});
yield* this._runHooks('after', 'update', options);
return this;
}
/**
* Get database for a model
*
* @api private
*/
static get _db () {
// support for multiple connections
// if model has a custom database assigned
// use it, otherwise use the default
return this.prototype.db || Mongorito.db;
}
/**
* Get collection for a model
*
* @api private
*/
static get _collection () {
if (is.string(this.prototype.collection)) {
return Mongorito._collection(this._db, this.prototype.collection);
}
// get collection name
// from the "collection" property
// or generate the default one
let defaultName = pluralize(this.name).toLowerCase()
let name = result(this.prototype, 'collection', defaultName);
// save collection name
// to avoid the same check in future
this.prototype.collection = name;
return Mongorito._collection(this._db, name);
}
/**
* Find documents
*
* @param {Object} query - find conditions, same as this.where()
* @api public
*/
static find (query) {
return new Query(this._collection, this).find(query); // collection, model
}
/**
* Count documents
*
* @param {Object} query - find conditions, same as this.where()
* @api public
*/
static count (query) {
return new Query(this._collection, this).count(query); // collection, model
}
/**
* Find all documents in a collection
*
* @api public
*/
static all () {
return this.find();
}
/**
* Find one document
*
* @param {Object} query - find conditions, same as this.where()
* @api public
*/
static * findOne (query) {
let docs = yield* this.find(query);
return docs[0];
}
/**
* Find a document by ID
*
* @param {ObjectID} id - document id
* @api public
*/
static findById (id) {
return this.findOne({ _id: id });
}
/**
* Remove documents
*
* @param {Object} query - remove conditions, same as this.where()
* @api public
*/
static remove (query) {
return new Query(this._collection, this).remove(query); // collection, model
}
/**
* Set up an index
*
* @see https://github.com/Automattic/monk#indexes
* @api public
*/
static * index () {
return yield this._collection.index(...arguments)
}
/**
* List all indexes
*
* @see https://github.com/Automattic/monk#indexes
* @api public
*/
static * indexes () {
return yield this._collection.indexes();
}
}
// Setting up functions that have
// the same implementation
// and act as a bridge to Query
const methods = [
'where',
'limit',
'skip',
'sort',
'exists',
'lt',
'lte',
'gt',
'gte',
'in',
'nin',
'and',
'or',
'ne',
'nor',
'populate'
];
methods.forEach(method => {
Model[method] = function () {
let query = new Query(this._collection, this); // collection, model
query[method].apply(query, arguments);
return query;
};
});
/**
* Backwards compatibility for ES5-ish way of defining models
*/
Model.extend = require('./extend')(Model);
/**
* Expose Mongorito
*/
var exports = module.exports = Mongorito;
exports.Model = Model;
Object.keys(mongoskin).forEach(key => {
if (['connect', 'version', 'db'].indexOf(key) === -1) {
exports[key] = mongoskin[key];
}
});
const emptyObject = {};