-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
51 lines (46 loc) · 1.75 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
var cls = require('continuation-local-storage');
var createNamespace = cls.createNamespace;
var mtMongooseSessionSet = createNamespace('mt-mongoose-session');
var defaultDb = null;
var systemDb = null;
var getNamespace = cls.getNamespace;
var MTMongoose = function () {
};
//Default tenant db which is used to perform useDB operation.
MTMongoose.prototype.setDefaultTenantDB = function (_defaultDB) {
defaultDb = _defaultDB;
};
//Utility Method to set system(non tenant specific DB) Use this method, so that the model usage across tenant specific and non tenant specific will look same.
MTMongoose.prototype.setGlobalDB = function (_systemDb) {
systemDb = _systemDb;
};
//Method used to set
MTMongoose.prototype.setTenantId = function (req, res, next) {
mtMongooseSessionSet.run(function () {
mtMongooseSessionSet.set("tenant_id", req._tid);
next();
});
};
MTMongoose.prototype.getTenantId = function () {
var mtMongooseSessionGet = getNamespace('mt-mongoose-session');
var tenant_id = mtMongooseSessionGet.get("tenant_id");
return tenant_id;
};
MTMongoose.prototype.getMTModel = function (schemaObj) {
var tenantDBId = this.getTenantId();
var tenantDB = defaultDb.useDb(tenantDBId ? tenantDBId : "test");
if (tenantDB) {
return tenantDB.model(schemaObj.modelName ? schemaObj.modelName : schemaObj.name, schemaObj.schema)
}
};
MTMongoose.prototype.getSystemModel = function (schemaObj) {
return systemDb.model(schemaObj.modelName ? schemaObj.modelName : schemaObj.name, schemaObj.schema)
};
MTMongoose.prototype.getModel = function (schemaObj) {
if(schemaObj.isGlobal){
return this.getSystemModel(schemaObj);
}else{
return this.getMTModel(schemaObj)
}
};
module.exports = new MTMongoose();