UNPKG

1.5 kBJavaScriptView Raw
1'use strict';
2
3module.exports = class Connections {
4 constructor(app) {
5 this.app = app;
6 this.connectors = {};
7 this.connections = {};
8 }
9
10 use({ type, connect } = {}) {
11 if (!type || typeof type !== 'string')
12 throw new Error('Invalid Kellner protocol type');
13 if (!connect || typeof connect !== 'function')
14 throw new Error('Invalid Kellner protocol');
15 this.connectors[type] = connect;
16 }
17
18 get(type, name) {
19 const cacheKey = name ? `${type}:${name}` : type;
20 if (!this.connections[cacheKey])
21 this.connections[cacheKey] = this.connect(type, name);
22
23 return this.connections[cacheKey];
24 }
25
26 async connect(type, name) {
27 if (!this.connectors[type])
28 throw new Error(`No protocol of type [${type}] defined.`);
29
30 const connection = await this.connectors[type](this.app.config, name);
31
32 if (connection.on) {
33 connection.on('close', e => this.app.fail(e));
34 connection.on('error', e => this.app.fail(e));
35 connection.on('disconnect', e => this.app.fail(e));
36 }
37
38 return connection;
39 }
40
41 async close() {
42 // eslint-disable-next-line no-restricted-syntax
43 for (const [cacheKey, connectionResolver] of Object.entries(this.connections)) {
44 // eslint-disable-next-line no-await-in-loop
45 const connection = await connectionResolver;
46 this.connections[cacheKey] = null;
47
48 if (connection.removeAllListeners)
49 connection.removeAllListeners();
50
51 if (connection.close)
52 // eslint-disable-next-line no-await-in-loop
53 await connection.close(true);
54
55 }
56 }
57};