-
Notifications
You must be signed in to change notification settings - Fork 2
/
manager.js
69 lines (56 loc) · 1.38 KB
/
manager.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
const Pool = require('./pool');
const Session = require('./session');
class Manager {
constructor ({ connections = [] } = {}) {
this.pools = {};
connections.forEach(connection => this.putPool(connection));
}
putPool (config) {
/* istanbul ignore if */
if (typeof config.adapter !== 'function') {
throw new Error('Adapter must be a constructor');
}
const pool = new Pool(config);
this.pools[pool.name] = pool;
this.main = this.main || pool.name;
return this;
}
/**
* Getter pool
*
* @param {string} name
* @returns {Pool}
*/
getPool (name) {
name = name || this.main;
if (!this.pools[name]) {
throw new Error(`Pool '${name}' not found`);
}
return this.pools[name];
}
async runSession (fn, options) {
const session = this.openSession(options);
try {
const result = await fn(session);
await session.close();
await session.dispose();
return result;
} catch (err) {
await session.dispose();
throw err;
}
}
openSession (options) {
return new Session({ manager: this, options });
}
/* istanbul ignore next */
async end () {
await Promise.all(Object.keys(this.pools).map(async name => {
const pool = this.pools[name];
await pool.drain();
await pool.clear();
}));
this.pools = {};
}
}
module.exports = Manager;