-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
110 lines (85 loc) · 2.26 KB
/
index.ts
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import Debug from 'debug'
import exitHook from 'exit-hook'
import type mssqlTypes from 'mssql'
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<string, mssqlTypes.ConnectionPool>()
function getPoolKey(config: mssqlTypes.config): string {
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: mssqlTypes.config
): Promise<mssqlTypes.ConnectionPool> {
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 as mssqlTypes.ConnectionPool
}
/**
* Release all open connection pools.
*/
export async function releaseAll(): Promise<void> {
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(): number {
return POOLS.size
}
/**
* Initialize shutdown.
*/
debug('Initializing shutdown hooks.')
exitHook(() => {
debug('Running shutdown hooks.')
void releaseAll()
})
/*
* Exports
*/
export default {
driver,
connect,
releaseAll,
getPoolCount
}
export type * as mssqlTypes from 'mssql'