64 lines
1.7 KiB
JavaScript
64 lines
1.7 KiB
JavaScript
|
|
const MongoClient = require('mongodb').MongoClient
|
|
|
|
function buildUri(urlOrOptions) {
|
|
if (!urlOrOptions || typeof urlOrOptions !== 'object') {
|
|
if (typeof urlOrOptions === 'string') {
|
|
return urlOrOptions;
|
|
}
|
|
throw new Error('buildUri: valid options or URI string required');
|
|
}
|
|
|
|
const hosts = Array.isArray(urlOrOptions.hosts)
|
|
? urlOrOptions.hosts.filter(Boolean).join(',')
|
|
: (urlOrOptions.hosts || 'localhost:27017');
|
|
const auth = urlOrOptions.user
|
|
? `${encodeURIComponent(urlOrOptions.user)}${urlOrOptions.pass ? `:${encodeURIComponent(urlOrOptions.pass)}` : ''}@`
|
|
: '';
|
|
const dbName = urlOrOptions.db || 'agmission';
|
|
const authSource = urlOrOptions.authSource || dbName;
|
|
|
|
const params = new URLSearchParams();
|
|
if (urlOrOptions.replicaSet) {
|
|
params.append('replicaSet', urlOrOptions.replicaSet);
|
|
}
|
|
if (authSource && authSource !== dbName) {
|
|
params.append('authSource', authSource);
|
|
}
|
|
const queryString = params.toString() ? `?${params.toString()}` : '';
|
|
|
|
return `mongodb://${auth}${hosts}/${dbName}${queryString}`;
|
|
}
|
|
|
|
/**
|
|
* Version-agnostic connectivity check using a ping command.
|
|
* Works with MongoDB driver 3.x, 4.x, 5+ (unlike isConnected() which was removed in v5).
|
|
* @param {MongoClient} client
|
|
* @returns {Promise<boolean>}
|
|
*/
|
|
async function isConnected(client) {
|
|
if (!client) return false;
|
|
try {
|
|
await client.db().admin().command({ ping: 1 });
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
async function connect(url) {
|
|
const _url = buildUri(url);
|
|
|
|
return await MongoClient.connect(_url, {
|
|
family: 4,
|
|
useNewUrlParser: true,
|
|
useUnifiedTopology: true,
|
|
keepAlive: true
|
|
});
|
|
}
|
|
|
|
module.exports = {
|
|
connect,
|
|
isConnected
|
|
}
|