-
Notifications
You must be signed in to change notification settings - Fork 25
/
index.js
533 lines (442 loc) · 13.9 KB
/
index.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
/**
* mongo-tenant - Multi-tenancy for mongoose on document level.
*
* @copyright Copyright (c) 2016-2017, craftup
* @license https://github.com/craftup/node-mongo-tenant/blob/master/LICENSE MIT
*/
'use strict';
/**
* MongoTenant is a class aimed for use in mongoose schema plugin scope.
* It adds support for multi-tenancy on document level (adding a tenant reference field and include this in unique indexes).
* Furthermore it provides an API for tenant bound models.
*
* @property {object} _modelCache
* @property {object} schema
*/
class MongoTenant {
/**
* Create a new mongo tenant from a given schema.
*
* @param {Object} [options] - A hash of configuration options.
* @param {boolean} [options.enabled] - Whether the mongo tenant plugin is enabled. Default: **true**.
* @param {string} [options.tenantIdKey] - The name of the tenant id field. Default: **tenantId**.
* @param {string|*} [options.tenantIdType] - The type of the tenant id field. Default: **String**.
* @param {string} [options.tenantIdGetter] - The name of the tenant id getter method. Default: **getTenantId**.
* @param {string} [options.accessorMethod] - The name of the tenant bound model getter method. Default: **byTenant**.
* @param {boolean} [options.requireTenantId] - Whether tenant id field should be required. Default: **false**.
*/
constructor(schema, options) {
this.options = options || {};
const modelCache = {};
Object.defineProperties(this, {
_modelCache: {
get: () => modelCache,
},
schema: {
get: () => schema,
}
});
}
/**
* Apply the mongo tenant plugin to the given schema.
*
* @returns {MongoTenant}
*/
apply() {
this
.extendSchema()
.compoundIndexes()
.injectApi()
.installMiddleWare();
}
/**
* Returns the boolean flag whether the mongo tenant is enabled.
*
* @returns {boolean}
*/
isEnabled() {
return !!(typeof this.options.enabled === "undefined" ? true : this.options.enabled);
}
/**
* Return the name of the tenant id field. Defaults to **tenantId**.
*
* @returns {string}
*/
getTenantIdKey() {
return this.options.tenantIdKey || 'tenantId';
}
/**
* Return the type of the tenant id field. Defaults to **String**.
*
* @returns {*|String}
*/
getTenantIdType() {
return this.options.tenantIdType || String;
}
/**
* Return the method name for accessing tenant-bound models.
*
* @returns {*|string}
*/
getAccessorMethod() {
return this.options.accessorMethod || 'byTenant';
}
/**
* Return the name of the tenant id getter method.
*
* @returns {*|string}
*/
getTenantIdGetter() {
return this.options.tenantIdGetter || 'getTenantId';
}
/**
* Check if tenant id is a required field.
*
* @return {boolean}
*/
isTenantIdRequired() {
return this.options.requireTenantId === true;
}
/**
* Checks if instance is compatible to other plugin instance
*
* For population of referenced models it's necessary to detect if the tenant
* plugin installed in these models is compatible to the plugin of the host
* model. If they are compatible they are one the same "level".
*
* @param {MongoTenant} plugin
*/
isCompatibleTo(plugin) {
return (
plugin &&
typeof plugin.getAccessorMethod === 'function' &&
typeof plugin.getTenantIdKey === 'function' &&
this.getTenantIdKey() === plugin.getTenantIdKey()
);
}
/**
* Inject tenantId field into schema definition.
*
* @returns {MongoTenant}
*/
extendSchema() {
if (this.isEnabled()) {
let tenantField = {
[this.getTenantIdKey()]: {
index: true,
type: this.getTenantIdType(),
required: this.isTenantIdRequired(),
}
};
this.schema.add(tenantField);
}
return this;
}
/**
* Consider the tenant id field in all unique indexes (schema- and field level).
* Take the optional **preserveUniqueKey** option into account for oupting out the default behaviour.
*
* @returns {MongoTenant}
*/
compoundIndexes() {
if (this.isEnabled()) {
// apply tenancy awareness to schema level unique indexes
this.schema._indexes.forEach((index) => {
// extend uniqueness of indexes by tenant id field
// skip if perserveUniqueKey of the index is set to true
if (index[1].unique === true && index[1].preserveUniqueKey !== true) {
let tenantAwareIndex = {
[this.getTenantIdKey()]: 1
};
for (let indexedField in index[0]) {
tenantAwareIndex[indexedField] = index[0][indexedField];
}
index[0] = tenantAwareIndex;
}
});
// apply tenancy awareness to field level unique indexes
this.schema.eachPath((key, path) => {
let pathOptions = path.options;
// skip if perserveUniqueKey of an unique field is set to true
if (pathOptions.unique === true && pathOptions.preserveUniqueKey !== true) {
// delete the old index
path._index = null;
delete path.options.unique;
// prepare new options
let indexOptions = {
unique: true
};
// add sparse option if set in options
if (pathOptions.sparse) {
indexOptions.sparse = true;
}
// add partialFilterExpression option if set in options
if (pathOptions.partialFilterExpression) {
indexOptions.partialFilterExpression = pathOptions.partialFilterExpression;
}
// create a new one that includes the tenant id field
this.schema.index({
[this.getTenantIdKey()]: 1,
[key]: 1
}, indexOptions);
}
});
}
return this;
}
/**
* Inject the user-space entry point for mongo tenant.
* This method adds a static Model method to retrieve tenant bound sub-classes.
*
* @returns {MongoTenant}
*/
injectApi() {
let me = this;
Object.assign(this.schema.statics, {
[this.getAccessorMethod()]: function (tenantId) {
if (!me.isEnabled()) {
return this.model(this.modelName);
}
let modelCache = me._modelCache[this.modelName] || (me._modelCache[this.modelName] = {});
// lookup tenant-bound model in cache
if (!modelCache[tenantId]) {
let Model = this.model(this.modelName);
// Cache the tenant bound model class.
modelCache[tenantId] = me.createTenantAwareModel(Model, tenantId);
}
return modelCache[tenantId];
},
get mongoTenant() {
return me;
}
});
return this;
}
/**
* Create a model class that is bound the given tenant.
* So that all operations on this model prohibit leaving the tenant scope.
*
* @param BaseModel
* @param tenantId
* @returns {MongoTenantModel}
*/
createTenantAwareModel(BaseModel, tenantId) {
let
tenantIdGetter = this.getTenantIdGetter(),
tenantIdKey = this.getTenantIdKey();
const db = this.createTenantAwareDb(BaseModel.db, tenantId);
class MongoTenantModel extends BaseModel {
static get hasTenantContext() {
return true;
}
static [tenantIdGetter]() {
return tenantId;
}
/**
* @see Mongoose.Model.aggregate
* @param {...Object|Array} [operations] aggregation pipeline operator(s) or operator array
* @param {Function} [callback]
* @return {Mongoose.Aggregate|Promise}
*/
static aggregate() {
let operations = Array.prototype.slice.call(arguments);
let pipeline = operations;
if (Array.isArray(operations[0])) {
pipeline = operations[0];
} else if (arguments.length === 1 || typeof arguments[1] === 'function') {
// mongoose 5.x compatibility
pipeline = operations[0] = [operations[0]];
}
pipeline.unshift({
$match: {
[tenantIdKey]: this[tenantIdGetter]()
}
});
return super.aggregate.apply(this, operations);
}
static deleteOne(conditions, callback) {
conditions[tenantIdKey] = this[tenantIdGetter]();
return super.deleteOne(conditions, callback);
}
static deleteMany(conditions, options, callback) {
conditions[tenantIdKey] = this[tenantIdGetter]();
return super.deleteMany(conditions, options, callback);
}
static remove(conditions, callback) {
if (arguments.length === 1 && typeof conditions === 'function') {
callback = conditions;
conditions = {};
}
conditions[tenantIdKey] = this[tenantIdGetter]();
return super.remove(conditions, callback);
}
static insertMany(docs, callback) {
let
me = this,
tenantId = this[tenantIdGetter]();
// Model.inserMany supports a single document as parameter
if (!Array.isArray(docs)) {
docs[tenantIdKey] = tenantId;
} else {
docs.forEach(function (doc, key) {
doc[tenantIdKey] = tenantId;
});
}
// ensure the returned docs are instanced of the bould multi tenant model
return super.insertMany(docs, (err, docs) => {
if (err) {
return callback && callback(err);
}
return callback && callback(null, docs.map(doc => new me(doc)));
});
}
static get db() {
return db;
}
get hasTenantContext() {
return true;
}
[tenantIdGetter]() {
return tenantId;
}
}
// inherit all static properties from the mongoose base model
for (let staticProperty of Object.getOwnPropertyNames(BaseModel)) {
if (MongoTenantModel.hasOwnProperty(staticProperty)
|| ['arguments', 'caller'].indexOf(staticProperty) !== -1
) {
continue;
}
let descriptor = Object.getOwnPropertyDescriptor(BaseModel, staticProperty);
Object.defineProperty(MongoTenantModel, staticProperty, descriptor);
}
// create tenant models for discriminators if they exist
if (BaseModel.discriminators) {
MongoTenantModel.discriminators = {};
for (let key in BaseModel.discriminators) {
MongoTenantModel.discriminators[key] = this.createTenantAwareModel(BaseModel.discriminators[key], tenantId);
}
}
return MongoTenantModel;
}
/**
* Create db connection bound to a specific tenant
*
* @param {Connection} unawareDb
* @param {*} tenantId
* @returns {Connection}
*/
createTenantAwareDb(unawareDb, tenantId) {
const me = this;
const awareDb = Object.create(unawareDb);
awareDb.model = (name) => {
const unawareModel = unawareDb.model(name);
const otherPlugin = unawareModel.mongoTenant;
if (!me.isCompatibleTo(otherPlugin)) {
return unawareModel;
}
return unawareModel[otherPlugin.getAccessorMethod()](tenantId);
};
return awareDb;
}
/**
* Install schema middleware to guard the tenant context of models.
*
* @returns {MongoTenant}
*/
installMiddleWare() {
let
me = this,
tenantIdGetter = this.getTenantIdGetter(),
tenantIdKey = this.getTenantIdKey();
this.schema.pre('count', function(next) {
if (this.model.hasTenantContext) {
this._conditions[tenantIdKey] = this.model[tenantIdGetter]();
}
next();
});
this.schema.pre('find', function(next) {
if (this.model.hasTenantContext) {
this._conditions[tenantIdKey] = this.model[tenantIdGetter]();
}
next();
});
this.schema.pre('countDocuments', function(next) {
if (this.model.hasTenantContext) {
this._conditions[tenantIdKey] = this.model[tenantIdGetter]();
}
next();
});
this.schema.pre('findOne', function(next) {
if (this.model.hasTenantContext) {
this._conditions[tenantIdKey] = this.model[tenantIdGetter]();
}
next();
});
this.schema.pre('findOneAndRemove', function(next) {
if (this.model.hasTenantContext) {
this._conditions[tenantIdKey] = this.model[tenantIdGetter]();
}
next();
});
this.schema.pre('findOneAndUpdate', function(next) {
if (this.model.hasTenantContext) {
me._guardUpdateQuery(this);
}
next();
});
this.schema.pre('save', function(next) {
if (this.constructor.hasTenantContext) {
this[tenantIdKey] = this.constructor[tenantIdGetter]();
}
next();
});
this.schema.pre('update', function(next) {
if (this.model.hasTenantContext) {
me._guardUpdateQuery(this);
}
next();
});
this.schema.pre('updateMany', function(next) {
if (this.model.hasTenantContext) {
me._guardUpdateQuery(this);
}
next();
});
return this;
}
/**
* Avoid breaking tenant context from update operations.
*
* @param {mongoose.Query} query
* @private
*/
_guardUpdateQuery(query) {
let
tenantIdGetter = this.getTenantIdGetter(),
tenantIdKey = this.getTenantIdKey(),
tenantId = query.model[tenantIdGetter](),
$set = query._update.$set;
query._conditions[tenantIdKey] = tenantId;
// avoid jumping tenant context when overwriting a model.
if ((tenantIdKey in query._update) || query.options.overwrite) {
query._update[tenantIdKey] = tenantId;
}
// avoid jumping tenant context from $set operations
if ($set && (tenantIdKey in $set) && $set[tenantIdKey] !== tenantId) {
$set[tenantIdKey] = tenantId;
}
}
}
/**
* The mongo tenant mongoose plugin.
*
* @param {mongoose.Schema} schema
* @param {Object} options
*/
function mongoTenantPlugin(schema, options) {
let mongoTenant = new MongoTenant(schema, options);
mongoTenant.apply();
}
mongoTenantPlugin.MongoTenant = MongoTenant;
module.exports = mongoTenantPlugin;