UNPKG

1.02 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};