wildduck/lib/db.js

82 lines
2.4 KiB
JavaScript
Raw Normal View History

'use strict';
2017-07-16 19:37:33 +08:00
const config = require('wild-config');
const tools = require('./tools');
const mongodb = require('mongodb');
2017-10-03 16:18:23 +08:00
const Redis = require('ioredis');
const MongoClient = mongodb.MongoClient;
module.exports.database = false;
module.exports.gridfs = false;
module.exports.users = false;
2017-07-17 21:32:31 +08:00
module.exports.senderDb = false;
module.exports.redis = false;
module.exports.redisConfig = false;
2017-07-17 21:32:31 +08:00
let getDBConnection = (main, config, callback) => {
if (main) {
if (!config) {
2017-12-21 19:31:01 +08:00
return callback(null, false);
2017-07-17 21:32:31 +08:00
}
if (config && !/[:/]/.test(config)) {
return callback(null, main.db(config));
}
}
2018-06-12 18:45:02 +08:00
MongoClient.connect(
config,
{
useNewUrlParser: true,
2020-01-03 19:30:42 +08:00
useUnifiedTopology: true
2018-06-12 18:45:02 +08:00
},
(err, db) => {
if (err) {
return callback(err);
}
if (main && db.s && db.s.options && db.s.options.dbName) {
db = db.db(db.s.options.dbName);
}
return callback(null, db);
2017-12-21 19:31:01 +08:00
}
2018-06-12 18:45:02 +08:00
);
2017-07-17 21:32:31 +08:00
};
2017-04-24 21:51:50 +08:00
2017-07-17 21:32:31 +08:00
module.exports.connect = callback => {
getDBConnection(false, config.dbs.mongo, (err, db) => {
if (err) {
return callback(err);
2017-04-24 21:51:50 +08:00
}
2017-12-21 19:31:01 +08:00
if (db.s && db.s.options && db.s.options.dbName) {
module.exports.database = db.db(db.s.options.dbName);
} else {
module.exports.database = db;
}
2017-12-20 21:17:34 +08:00
getDBConnection(db, config.dbs.gridfs, (err, gdb) => {
2017-04-24 21:51:50 +08:00
if (err) {
return callback(err);
}
2017-12-21 19:31:01 +08:00
module.exports.gridfs = gdb || module.exports.database;
2017-12-20 21:17:34 +08:00
getDBConnection(db, config.dbs.users, (err, udb) => {
2017-07-17 21:32:31 +08:00
if (err) {
return callback(err);
}
2017-12-21 19:31:01 +08:00
module.exports.users = udb || module.exports.database;
2017-12-20 21:17:34 +08:00
getDBConnection(db, config.dbs.sender, (err, sdb) => {
2017-07-17 21:32:31 +08:00
if (err) {
return callback(err);
}
2017-12-21 19:31:01 +08:00
module.exports.senderDb = sdb || module.exports.database;
2017-07-17 21:32:31 +08:00
module.exports.redisConfig = tools.redisConfig(config.dbs.redis);
2017-10-03 16:18:23 +08:00
module.exports.redis = new Redis(module.exports.redisConfig);
2017-07-17 21:32:31 +08:00
2018-08-15 03:45:18 +08:00
module.exports.redis.connect(() => callback(null, module.exports.database));
2017-07-17 21:32:31 +08:00
});
});
2017-04-24 21:51:50 +08:00
});
});
};