我有一个应用需要支持来自不同域的请求。
所有域的代码需要相同但不同的数据库。
我有一个Mongodb客户端的变形类女巫给模型连接。
有没有办法在这个类中获取请求的域名而不从任何对该函数的调用发送它(我在不同的服务中有很多调用)
请查看getDb函数的注释以了解我的需求
由于
const MongoClient = require('mongodb')
const assert = require('assert');
let MongoInstance = null;
class Mongo {
constructor(connectionString = null, connectionOptions = {}) {
if (MongoInstance === null) {
MongoInstance = this;
}
this.connectionString = connectionString;
this.connectionOptions = connectionOptions;
this._db = {};
return MongoInstance;
}
buildConnectionString() {
if (this.connectionString !== null) {
return;
}
this.connectionString = 'mongodb://';
this.connectionString += process.env.MONGODB_USERNAME ? `${process.env.MONGODB_USERNAME}:${process.env.MONGODB_PASSWORD}@` : '';
this.connectionString += process.env.MONGODB_HOST;
this.connectionString += process.env.MONGODB_PORT ? process.env.MONGODB_PORT : "";
}
connectToServer() {
return new Promise((resolve, reject) => {
this.buildConnectionString();
MongoClient.connect(this.connectionString, this.connectionOptions, (err, db) => {
if (err) {
return reject(err);
}
process.env.MONGODB_LIST.split(",").forEach(dbName =>{
this._db[dbName] = db.db(dbName);
})
resolve(true)
});
})
}
getDb() {
// how to discover the dbName without sending it to the function. (maybe a middleware)?
return this._db[dbName];
}
closeConnection() {
this._db.close();
}
}
module.exports = Mongo;