phase 1 rework
This commit is contained in:
1 parent
211bfd174d
commit
20054198f3
38 files changed
+5001
-1019
No files matched your search
+34
-10
@@ -1,14 +1,38 @@
|
||||
const { MongoClient } = require("mongodb");
|
||||
require("dotenv").config();
|
||||
const { MongoClient } = require('mongodb');
|
||||
const { config } = require('./config');
|
||||
|
||||
let client, db;
|
||||
function createDbProvider({ settings = config, MongoClientClass = MongoClient } = {}) {
|
||||
let client = null;
|
||||
let pending = null;
|
||||
|
||||
exports.getDb = async function () {
|
||||
if (db) return db;
|
||||
async function getDb() {
|
||||
if (!settings.mongoUri) throw new Error('MONGO_URI must be configured.');
|
||||
if (!pending) {
|
||||
let candidate;
|
||||
pending = Promise.resolve().then(async () => {
|
||||
candidate = new MongoClientClass(settings.mongoUri);
|
||||
client = candidate;
|
||||
await candidate.connect();
|
||||
return candidate.db(settings.mongoDb);
|
||||
}).catch(async () => {
|
||||
pending = null;
|
||||
client = null;
|
||||
if (candidate) await Promise.resolve().then(() => candidate.close()).catch(() => {});
|
||||
throw new Error('Database connection failed. Check the server configuration.');
|
||||
});
|
||||
}
|
||||
return pending;
|
||||
}
|
||||
|
||||
client = new MongoClient(process.env.MONGO_URI);
|
||||
await client.connect();
|
||||
async function closeDb() {
|
||||
if (pending) await pending.catch(() => {});
|
||||
const previous = client;
|
||||
client = null;
|
||||
pending = null;
|
||||
if (previous) await previous.close();
|
||||
}
|
||||
|
||||
db = client.db("downloads");
|
||||
return db;
|
||||
};
|
||||
return { getDb, closeDb };
|
||||
}
|
||||
|
||||
module.exports = { ...createDbProvider(), createDbProvider };
|
||||
Reference in new issue
Block a user