This repository has been archived by the owner on Feb 10, 2022. It is now read-only.
/
mongorito.js
806 lines (629 loc) · 16.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
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
/**
* Dependencies
*/
'use strict';
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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
*/
var Mongorito = (function () {
function Mongorito() {
_classCallCheck(this, Mongorito);
}
/**
* Connect to a MongoDB database and return connection object
*
* @param {String} urls - connection urls (as arguments)
* @api public
*/
Mongorito.connect = function connect() {
for (var _len = arguments.length, urls = Array(_len), _key = 0; _key < _len; _key++) {
urls[_key] = arguments[_key];
}
// convert mongo:// urls to monk-supported ones
urls = urls.map(function (url) {
return url.replace(/^mongo\:\/\//, '');
});
var db = monk.apply(undefined, 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
*/
Mongorito.disconnect = function disconnect() {
this.db.close();
};
/**
* Alias for .disconnect()
*
* @api public
*/
Mongorito.close = function close() {
return this.disconnect.apply(this, arguments);
};
/**
* Return a co-wrapped monk collection
*
* @api private
*/
Mongorito._collection = function _collection(db, name) {
var url = db.driver._connect_args[0];
var collections = this._collections[url];
if (!collections) {
collections = this._collections[url] = {};
}
if (collections[name]) return collections[name];
var collection = db.get(name);
collections[name] = wrap(collection);
return collections[name];
};
return Mongorito;
})();
/**
* Cache for monk collections
*
* @api private
*/
Mongorito._collections = {};
/**
* Model
*/
var Model = (function () {
function Model() {
var attrs = arguments[0] === undefined ? {} : arguments[0];
var options = arguments[1] === undefined ? {} : arguments[1];
_classCallCheck(this, Model);
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 model attribute
*
* @param {String} key - property name
* @api public
*/
Model.prototype.get = function get(key) {
var 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
*/
Model.prototype.set = function set(key, value) {
var _this = this;
// if object passed instead of key-value pair
// iterate and call set on each item
if (is.object(key)) {
var _ret = (function () {
var attrs = key;
var keys = Object.keys(attrs);
keys.forEach(function (key) {
_this.set(key, attrs[key]);
});
return {
v: undefined
};
})();
if (typeof _ret === 'object') return _ret.v;
}
// 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
*/
Model.prototype._setDefaults = function _setDefaults() {
var _this2 = this;
var defaults = result(this, 'defaults', {});
var keys = Object.keys(defaults);
keys.forEach(function (key) {
var defaultValue = defaults[key];
var actualValue = _this2.get(key);
if (is.undefined(actualValue)) {
_this2.set(key, defaultValue);
}
});
};
/**
* Get all attributes
*
* @api public
*/
Model.prototype.toJSON = function toJSON() {
return this.attributes;
};
/**
* Configure model (usually, set hooks here)
* Supposed to be overriden
*
* @api public
*/
Model.prototype.configure = function configure() {};
/**
* Rollback given method when error occurs
* Supposed to be overriden
*
* @param {String} name - method name
* @api public
*/
Model.prototype.rollback = function* rollback() {};
/**
* Return a function, that in case of an error
* executes this.rollback() with a given method name
*
* @api private
*/
Model.prototype._rollbackFor = function _rollbackFor(method) {
return function* (next) {
try {
yield* next;
} catch (err) {
yield this.rollback(method);
throw err;
}
};
};
/**
* Add hooks
*
* @api private
*/
Model.prototype.hook = function hook(when, action, method) {
var _this3 = this;
// if object is given
// iterate and call .hook()
// for each entry
if (is.object(when)) {
var _ret2 = (function () {
var hooks = when;
var keys = Object.keys(hooks);
keys.forEach(function (key) {
var _key$split = key.split(':');
var when = _key$split[0];
var action = _key$split[1];
var method = hooks[key];
_this3.hook(when, action, method);
});
return {
v: undefined
};
})();
if (typeof _ret2 === 'object') return _ret2.v;
}
// if array is given
// iterate and call .hook()
// for each item
if (is.array(method)) {
var _methods = method;
_methods.forEach(function (method) {
return _this3.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
*/
Model.prototype.hooks = function hooks() {
return this.hook.apply(this, arguments);
};
/**
* Add before:* hook
*
* @param {String} action - before what
* @param {String} method - hook name
* @api public
*/
Model.prototype.before = function before(action, method) {
this.hook('before', action, method);
};
/**
* Add after:* hook
*
* @param {String} action - after what
* @param {String} method - hook name
* @api public
*/
Model.prototype.after = function after(action, method) {
this.hook('after', action, method);
};
/**
* Add around:* hook
*
* @param {String} action - around what
* @param {String} method - hook name
* @api public
*/
Model.prototype.around = function around(action, method) {
this.hook('around', action, method);
};
/**
* Execute hooks
*
* @api private
*/
Model.prototype._runHooks = function _runHooks(when, action) {
var _this4 = this;
var options = arguments[2] === undefined ? {} : arguments[2];
var hooks = this._getHooks(when, action);
// skip hooks
var skip = options.skip;
if (skip) {
if (is.string(skip)) skip = [skip];
hooks = hooks.filter(function (fn) {
return skip.indexOf(fn.name) === -1;
});
}
var middleware = [];
// insert a rollback fn
// before each hook
hooks.forEach(function (fn) {
var rollback = _this4._rollbackFor(fn.name);
middleware.push(rollback, fn);
});
return compose(middleware).call(this);
};
/**
* Get hooks for a given operation
*
* @api private
*/
Model.prototype._getHooks = function _getHooks(when, action) {
var 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
*/
Model.prototype.save = function* save(options) {
var _this5 = this;
// set default values if needed
this._setDefaults();
var id = this.get('_id');
var fn = id ? this.update : this.create;
// revert populated documents to _id's
var populate = this.options.populate || emptyObject;
var keys = Object.keys(populate);
keys.forEach(function (key) {
var value = _this5.get(key);
if (is.array(value)) {
value = value.map(function (doc) {
return doc.get('_id');
});
} else {
value = value.get('_id');
}
_this5.set(key, value);
});
return yield fn.call(this, options);
};
/**
* Create a model
*
* @api private
*/
Model.prototype.create = function* create(options) {
var collection = this._collection;
var attrs = this.attributes;
var date = new Date();
this.set({
created_at: date,
updated_at: date
});
yield* this._runHooks('before', 'create', options);
var doc = yield collection.insert(attrs);
this.set('_id', doc._id);
yield* this._runHooks('after', 'create', options);
return this;
};
/**
* Update a model
*
* @api private
*/
Model.prototype.update = function* update(options) {
var collection = this._collection;
var 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
*/
Model.prototype.remove = function* remove(options) {
var 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
*/
Model.prototype.inc = function* inc(props, options) {
var _this6 = this;
var id = this.get('_id');
if (!id) {
throw new Error('Can\'t atomically increment a property of unsaved document.');
}
var 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(function (key) {
// get current value
var value = _this6.get(key);
// perform increment
value += props[key];
// save
_this6.set(key, value);
});
yield* this._runHooks('after', 'update', options);
return this;
};
/**
* Find documents
*
* @param {Object} query - find conditions, same as this.where()
* @api public
*/
Model.find = function 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
*/
Model.count = function count(query) {
return new Query(this._collection, this).count(query); // collection, model
};
/**
* Find all documents in a collection
*
* @api public
*/
Model.all = function all() {
return this.find();
};
/**
* Find one document
*
* @param {Object} query - find conditions, same as this.where()
* @api public
*/
Model.findOne = function* findOne(query) {
var docs = yield* this.find(query);
return docs[0];
};
/**
* Find a document by ID
*
* @param {ObjectID} id - document id
* @api public
*/
Model.findById = function findById(id) {
return this.findOne({ _id: id });
};
/**
* Remove documents
*
* @param {Object} query - remove conditions, same as this.where()
* @api public
*/
Model.remove = function remove(query) {
return new Query(this._collection, this).remove(query); // collection, model
};
/**
* Drop collection
*
* @api public
*/
Model.drop = function* drop() {
yield this._collection.drop();
};
/**
* Set up an index
*
* @see https://github.com/Automattic/monk#indexes
* @api public
*/
Model.index = function* index() {
var _collection;
return yield (_collection = this._collection).index.apply(_collection, arguments);
};
/**
* List all indexes
*
* @see https://github.com/Automattic/monk#indexes
* @api public
*/
Model.indexes = function* indexes() {
return yield this._collection.indexes();
};
_createClass(Model, [{
key: '_collection',
/**
* Get collection for current model
*
* @api private
*/
get: function () {
if (is.string(this.collection)) {
return Mongorito._collection(this._db, this.collection);
}
// get collectio name
// from the "collection" property
// or generate the default one
var defaultName = pluralize(this.constructor.name).toLowerCase();
var 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);
}
}, {
key: '_db',
/**
* Get database for current model
*
* @api private
*/
get: function () {
// use either custom database
// specified for this model
// or use a default one
return this.db || Mongorito.db;
}
}], [{
key: '_db',
/**
* Get database for a model
*
* @api private
*/
get: function () {
// support for multiple connections
// if model has a custom database assigned
// use it, otherwise use the default
return this.prototype.db || Mongorito.db;
}
}, {
key: '_collection',
/**
* Get collection for a model
*
* @api private
*/
get: function () {
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
var defaultName = pluralize(this.name).toLowerCase();
var 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);
}
}]);
return Model;
})();
// 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', 'matches', 'match', 'include', 'exclude', 'search'];
methods.forEach(function (method) {
Model[method] = function () {
var 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(function (key) {
if (['connect', 'version', 'db'].indexOf(key) === -1) {
_exports[key] = mongoskin[key];
}
});
const emptyObject = {};