multibridge
Version:
A multi-database connection framework with centralized configuration
45 lines (44 loc) • 2.17 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createMongoDBConnection = createMongoDBConnection;
const mongodb_1 = require("mongodb");
const loggers_1 = __importDefault(require("../utils/loggers"));
function createMongoDBConnection(config) {
return __awaiter(this, void 0, void 0, function* () {
var _a;
let uri;
if (config.host.endsWith(".mongodb.net")) {
// MongoDB Atlas (Cluster) using SRV
uri = `mongodb+srv://${config.username}:${config.password}@${config.host}/${config.database}?authSource=admin`;
}
else {
// Self-hosted MongoDB (Local/Remote)
uri = `mongodb://${config.username}:${config.password}@${config.host}:${(_a = config.port) !== null && _a !== void 0 ? _a : 27017}/${config.database}?authSource=admin`;
}
const client = new mongodb_1.MongoClient(uri, {
connectTimeoutMS: 10000,
serverSelectionTimeoutMS: 10000,
});
try {
yield client.connect();
loggers_1.default.info(`Connected to MongoDB at ${config.host}`);
return client.db(config.database);
}
catch (error) {
loggers_1.default.error(`Error connecting to MongoDB: ${error.message}`);
throw error;
}
});
}