import { IMongoConfig, IMongoConnectionConfig, IMongoConnectionOptions } from "./interfaces"; import { getMongoConnectionConfig } from "./mongo-connection-config-builder"; const aws_secret_manager = require("../aws-secret-manager/aws-secret-manager"); const { MongoClient } = require('mongodb'); const mstime = require('mstime'); let randomNumber = () => { return ((Math.random() * 0x100000000) >>> 0) + 'NODE' + ((Math.random() * 0x100000000) >>> 0) } /** * Function to create connection and return it. It fetches the configs from the global config which are set during initialization of application * @stable * @async * @param mongoInstance : since single service can have multiple mongo db connections * @param instanceKey */ export const createConnection = async (mongoInstance : string = 'default', instanceKey: string = 'default') => { let config = getMongoConnectionConfig(mongoInstance, instanceKey); return createCustomConnection(config); } /** * Function to be consumed by the internally for building the connection, please use this if you want to pass custom config only * @internal * @stable * @async * @param config * @param secretName */ export const createCustomConnection = async(config : IMongoConnectionConfig) => { let id = randomNumber(); mstime.start(id); try{ let secretData = await aws_secret_manager.secretPromise("",config.awsSecretKey); const password = secretData[config.mongoConfig.username]; const connectionUrl = getConnectionUrl(config, password); console.log("Creating Mongo Connection with uri : " + connectionUrl); let connection = await MongoClient.connect(connectionUrl); let result = mstime.end(id); console.log(`Successfully connected to Mongo, 🕒 Time taken: ${result.last} ms`); return connection; } catch(err) { console.log("Error connecting mongo : " + err); } } /** * Function to disconnect from mongodb * @stable * @async * @param connection */ export const destroyConnection = async (connection: any) => { console.log(`Disconnected with Mongo`); try { await connection.close(); console.log(`Successfully disconnected to Mongo`); } catch(err) { console.log("Error disconnecting mongo : " + err); } } const getConnectionUrl = (config : IMongoConnectionConfig, password : string ) : string => { let mongoConfig = config.mongoConfig; let connectionUrl = mongoConfig.protocol + "://" + mongoConfig.username + ":" + password + "@" + mongoConfig.hostname; let options = getConnectionOptionsString(config.mongoConnectionOptions); connectionUrl = connectionUrl + "?" + options; return connectionUrl; } const getConnectionOptionsString = (connectionOptions : IMongoConnectionOptions) : string => { let connectionOptionMap = Object.entries(connectionOptions); let optionsString = ""; let firstVariable = true; for (let [key, value] of connectionOptionMap) { if(!firstVariable) { optionsString += "&"; } firstVariable = false; optionsString += key + "=" + value; } console.log("Options String : " + optionsString); return optionsString; }