@azteam/mongo-model
Version:
N/A
106 lines (89 loc) • 2.74 kB
JavaScript
import _ from 'lodash';
import mongoose from 'mongoose';
function registerConnection(config) {
let url = `mongodb://`;
config.shard.map((item, key) => {
if (key > 0) {
url += ',';
}
url += `${item.host}:${item.port || 27017}`;
return url;
});
if (config.replicaSet) {
url += `?replicaSet=${config.replicaSet}&readPreference=${config.readPreference || 'primary'}`;
}
const options = {
dbName: config.prefix ? `${config.prefix}:${config.database}` : config.database,
user: config.username,
pass: config.password,
maxPoolSize: config.pool ? config.pool : 10,
minPoolSize: 0,
directConnection: true,
heartbeatFrequencyMS: 1000,
socketTimeoutMS: 45000,
serverSelectionTimeoutMS: 5000,
};
try {
return mongoose.createConnection(url, options);
} catch (e) {
console.error('error', e);
}
return false;
}
class Provider {
constructor(configs = []) {
this.model = {};
this.connections = {};
this.configs = {};
this.redis = null;
if (Array.isArray(configs)) {
configs.map((config) => {
this.configs[config.name] = config;
return true;
});
} else {
this.configs.main = configs;
}
}
setRedis(redis) {
this.redis = redis;
}
async waitAllConnection() {
await Promise.all(
Object.keys(this.configs).map((keyConfig) => {
return this.getConnection(keyConfig);
})
);
}
closeAll() {
_.map(this.connections, (connection) => {
connection.close();
});
}
bindingModel(model, dbName = 'main') {
if (!this.model[model.name]) {
const connection = this.getConnection(dbName);
this.model[model.name] = model.register(connection);
}
if (!this.model[`Trash${model.name}`]) {
const connection = this.getConnection(dbName);
this.model[`Trash${model.name}`] = model.register(connection, true); // is trash
}
return {
activeModel: this.model[model.name],
trashModel: this.model[`Trash${model.name}`],
redis: this.redis,
};
}
getConnection(name = 'main') {
if (!this.connections[name]) {
if (this.configs[name]) {
this.connections[name] = registerConnection(this.configs[name]);
} else {
return this.getConnection('main');
}
}
return this.connections[name];
}
}
export default Provider;