mirror of
https://github.com/awatertrevi/infisical.git
synced 2026-10-12 21:29:20 +00:00
44 lines
1.2 KiB
TypeScript
44 lines
1.2 KiB
TypeScript
import mongoose from 'mongoose';
|
|
import { getLogger } from '../utils/logger';
|
|
|
|
/**
|
|
* Initialize database connection
|
|
* @param {Object} obj
|
|
* @param {String} obj.mongoURL - mongo connection string
|
|
* @returns
|
|
*/
|
|
export const initDatabaseHelper = async ({
|
|
mongoURL
|
|
}: {
|
|
mongoURL: string;
|
|
}) => {
|
|
try {
|
|
await mongoose.connect(mongoURL);
|
|
|
|
// allow empty strings to pass the required validator
|
|
mongoose.Schema.Types.String.checkRequired(v => typeof v === 'string');
|
|
|
|
(await getLogger("database")).info("Database connection established");
|
|
|
|
} catch (err) {
|
|
(await getLogger("database")).error(`Unable to establish Database connection due to the error.\n${err}`);
|
|
}
|
|
|
|
return mongoose.connection;
|
|
}
|
|
|
|
/**
|
|
* Close database conection
|
|
*/
|
|
export const closeDatabaseHelper = async () => {
|
|
return Promise.all([
|
|
new Promise((resolve) => {
|
|
if (mongoose.connection && mongoose.connection.readyState == 1) {
|
|
mongoose.connection.close()
|
|
.then(() => resolve('Database connection closed'));
|
|
} else {
|
|
resolve('Database connection already closed');
|
|
}
|
|
})
|
|
]);
|
|
} |