2023-01-06 00:58:55 +01:00
|
|
|
const { MongoClient } = require('mongodb');
|
|
|
|
const {
|
|
|
|
MONGO_HOST,
|
|
|
|
MONGO_PORT,
|
|
|
|
MONGO_USER,
|
|
|
|
MONGO_PASS,
|
|
|
|
MONGO_DB,
|
|
|
|
} = process.env;
|
|
|
|
|
|
|
|
const uri = `mongodb://${MONGO_USER}:${MONGO_PASS}@${MONGO_HOST}:${MONGO_PORT}/?maxPoolSize=20`;
|
|
|
|
|
2023-01-15 18:42:26 +01:00
|
|
|
const getMongoConnection = async() => {
|
|
|
|
const client = new MongoClient(uri);
|
|
|
|
return await client.connect();
|
|
|
|
};
|
|
|
|
|
|
|
|
const getMongoDatabase = (client, db) => {
|
|
|
|
const DB = db || MONGO_DB;
|
|
|
|
return client.db(DB);
|
|
|
|
};
|
|
|
|
|
2023-01-22 00:02:30 +01:00
|
|
|
const mongoExecute = async function(fn, opts) {
|
|
|
|
const { dbName, colName } = { dbName: MONGO_DB, ...opts };
|
|
|
|
let connection;
|
2023-01-15 18:42:26 +01:00
|
|
|
try {
|
2023-01-22 00:02:30 +01:00
|
|
|
connection = await getMongoConnection();
|
|
|
|
const database = connection.db(dbName);
|
|
|
|
if (colName) {
|
|
|
|
const collection = database.collection(colName);
|
|
|
|
return await fn({ collection, database, connection });
|
|
|
|
}
|
|
|
|
return await fn({ database, connection });
|
2023-01-15 18:42:26 +01:00
|
|
|
} catch (err) {
|
2023-01-22 00:02:30 +01:00
|
|
|
console.log('err :>> ', err);
|
2023-01-15 18:42:26 +01:00
|
|
|
console.log('MOMGODB ERROR:', err.message);
|
|
|
|
} finally {
|
2023-01-22 00:02:30 +01:00
|
|
|
if (connection) {
|
|
|
|
await connection.close();
|
2023-01-15 18:42:26 +01:00
|
|
|
}
|
2023-01-06 00:58:55 +01:00
|
|
|
}
|
2023-01-15 18:42:26 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
mongoExecute,
|
|
|
|
getMongoConnection,
|
|
|
|
getMongoDatabase,
|
2023-01-06 00:58:55 +01:00
|
|
|
};
|