-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
79 lines (79 loc) · 2.11 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import Debug from 'debug';
import exitHook from 'exit-hook';
const debug = Debug('mssql-multi-pool:index');
/**
* The driver that will be used.
* - msnodesqlv8 on Windows.
* - tedious or all other operating systems.
*/
export const driver = process.platform === 'win32' ? 'msnodesqlv8' : 'tedious';
debug(`MSSQL driver: ${driver}`);
const mssqlImport = driver === 'msnodesqlv8'
? await import('mssql/msnodesqlv8.js')
: await import('mssql');
// eslint-disable-next-line @typescript-eslint/prefer-destructuring
const mssql = mssqlImport.default;
const POOLS = new Map();
function getPoolKey(config) {
return `${config.user ?? ''}@${config.server}/${config.options?.instanceName ?? ''};${config.database ?? ''}`;
}
/**
* Connect to a MSSQL database.
* Creates a new connection if the configuration does not match a seen configuration.
* @param config - MSSQL configuration.
* @returns A MSSQL connection pool.
*/
export async function connect(config) {
const poolKey = getPoolKey(config);
let pool = POOLS.get(poolKey);
if (!(pool?.connected ?? false)) {
debug(`New database connection: ${poolKey}`);
pool = new mssql.ConnectionPool(config);
await pool.connect();
POOLS.set(poolKey, pool);
}
return pool;
}
/**
* Release all open connection pools.
*/
export async function releaseAll() {
debug(`Releasing ${POOLS.size.toString()} pools.`);
for (const poolKey of POOLS.keys()) {
debug(`Releasing pool: ${poolKey}`);
try {
const pool = POOLS.get(poolKey);
if (pool !== undefined) {
await pool.close();
}
}
catch {
debug('Error closing connections.');
}
}
POOLS.clear();
}
/**
* Retrieves the number of managed connection pools.
* @returns The number of pools.
*/
export function getPoolCount() {
return POOLS.size;
}
/**
* Initialize shutdown.
*/
debug('Initializing shutdown hooks.');
exitHook(() => {
debug('Running shutdown hooks.');
void releaseAll();
});
/*
* Exports
*/
export default {
driver,
connect,
releaseAll,
getPoolCount
};