53 lines
1.2 KiB
JavaScript
53 lines
1.2 KiB
JavaScript
import { MongoClient } from "mongodb";
|
|
import { getConfig, getMongoUri, hasMongoConfig } from "./config.js";
|
|
|
|
const DEFAULT_DB_NAME = "arena_picker";
|
|
|
|
let mongoClient;
|
|
let mongoClientPromise;
|
|
|
|
export { hasMongoConfig };
|
|
|
|
export async function getMongoClient() {
|
|
if (mongoClient) {
|
|
return mongoClient;
|
|
}
|
|
|
|
if (!mongoClientPromise) {
|
|
const appConfig = getConfig();
|
|
const client = new MongoClient(getMongoUri(), {
|
|
maxPoolSize: appConfig.MONGODB_MAX_POOL_SIZE,
|
|
serverSelectionTimeoutMS: appConfig.MONGODB_SERVER_SELECTION_TIMEOUT_MS,
|
|
});
|
|
|
|
mongoClientPromise = client
|
|
.connect()
|
|
.then((connectedClient) => {
|
|
mongoClient = connectedClient;
|
|
return connectedClient;
|
|
})
|
|
.catch((error) => {
|
|
mongoClientPromise = undefined;
|
|
throw error;
|
|
});
|
|
}
|
|
|
|
return mongoClientPromise;
|
|
}
|
|
|
|
export async function getDb() {
|
|
const client = await getMongoClient();
|
|
return client.db(getConfig().MONGODB_DB || DEFAULT_DB_NAME);
|
|
}
|
|
|
|
export async function closeMongoConnection() {
|
|
if (!mongoClient && !mongoClientPromise) {
|
|
return;
|
|
}
|
|
|
|
const client = mongoClient || (await mongoClientPromise);
|
|
mongoClient = undefined;
|
|
mongoClientPromise = undefined;
|
|
await client.close();
|
|
}
|