49 lines
1.7 KiB
JavaScript
49 lines
1.7 KiB
JavaScript
import path from "path";
|
|
import grabDirNames from "../data/grab-dir-names";
|
|
import {} from "../types";
|
|
import { SQL } from "bun";
|
|
/** Reuse one client per database name to avoid exhausting MariaDB connections. */
|
|
const clientCache = new Map();
|
|
export default function grabMariaDBClient({ config, }) {
|
|
const cacheKey = config.db_name || "__default__";
|
|
const cached = clientCache.get(cacheKey);
|
|
if (cached) {
|
|
return cached;
|
|
}
|
|
// Prefer the process-wide client when it matches the requested database
|
|
if (global.MARIADB_CLIENT &&
|
|
(!global.CONFIG?.db_name || global.CONFIG.db_name === config.db_name)) {
|
|
clientCache.set(cacheKey, global.MARIADB_CLIENT);
|
|
return global.MARIADB_CLIENT;
|
|
}
|
|
const { ROOT_DIR } = grabDirNames();
|
|
try {
|
|
const tls = config.ssl_ca
|
|
? {
|
|
ca: Bun.file(path.resolve(ROOT_DIR, config.ssl_ca)),
|
|
rejectUnauthorized: false,
|
|
}
|
|
: {
|
|
rejectUnauthorized: false,
|
|
};
|
|
const MariaDBClient = new SQL({
|
|
hostname: process.env.BUN_MARIADB_SERVER_HOST,
|
|
username: process.env.BUN_MARIADB_SERVER_USERNAME,
|
|
password: process.env.BUN_MARIADB_SERVER_PASSWORD,
|
|
database: config.db_name,
|
|
port: process.env.BUN_MARIADB_SERVER_PORT
|
|
? Number(process.env.BUN_MARIADB_SERVER_PORT)
|
|
: undefined,
|
|
...config.db_config,
|
|
tls,
|
|
adapter: "mariadb",
|
|
});
|
|
clientCache.set(cacheKey, MariaDBClient);
|
|
return MariaDBClient;
|
|
}
|
|
catch (error) {
|
|
console.error(`Couldn't grab MariaDB Client => ` + error.message);
|
|
return;
|
|
}
|
|
}
|