u
This commit is contained in:
66
src/db/store.js
Normal file
66
src/db/store.js
Normal file
@@ -0,0 +1,66 @@
|
||||
import sql from 'mssql';
|
||||
import LibDashStore from 'libdashstore';
|
||||
import env from '../config/env.js';
|
||||
|
||||
let pool;
|
||||
let store;
|
||||
let connecting;
|
||||
|
||||
function getMssqlConfig() {
|
||||
const { server, database, user, password, port, encrypt, trustServerCertificate } = env.mssql;
|
||||
|
||||
if (!server || !database || !user || !password) {
|
||||
throw new Error('MSSQL is not configured (MSSQL_SERVER, MSSQL_DATABASE, MSSQL_USER, MSSQL_PASSWORD required)');
|
||||
}
|
||||
|
||||
return {
|
||||
server,
|
||||
database,
|
||||
user,
|
||||
password,
|
||||
port,
|
||||
pool: {
|
||||
max: 10,
|
||||
min: 0,
|
||||
idleTimeoutMillis: 30_000,
|
||||
},
|
||||
options: {
|
||||
encrypt,
|
||||
trustServerCertificate,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the initialized LibDashStore singleton.
|
||||
* @returns {Promise<InstanceType<typeof LibDashStore>>}
|
||||
*/
|
||||
export async function getStore() {
|
||||
if (store) {
|
||||
return store;
|
||||
}
|
||||
|
||||
if (!connecting) {
|
||||
connecting = (async () => {
|
||||
pool = await new sql.ConnectionPool(getMssqlConfig()).connect();
|
||||
store = await new LibDashStore(pool);
|
||||
return store;
|
||||
})().finally(() => {
|
||||
connecting = undefined;
|
||||
});
|
||||
}
|
||||
|
||||
return connecting;
|
||||
}
|
||||
|
||||
export async function ensureConnection() {
|
||||
await getStore();
|
||||
}
|
||||
|
||||
export async function closeStore() {
|
||||
if (pool) {
|
||||
await pool.close();
|
||||
pool = undefined;
|
||||
store = undefined;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user