-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathamqp-connection.js
64 lines (48 loc) · 1.58 KB
/
amqp-connection.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
const amqplib = require('amqplib');
const { v4: uuidv4 } = require('uuid');
module.exports = function(connectionString) {
this.connectionString = connectionString;
this.onCloseHandler = {};
this.connect = async function() {
console.log('connect!!!');
this.connection = await createConnection(this.connectionString);
this.connection.on("close", async () => {
this.connection = undefined;
const onCloseHandler = this.onCloseHandler;
this.onCloseHandler = {};
const promises = [];
for (const [key, handler] of Object.entries(onCloseHandler)) {
promises.push(handler());
}
await this.connect();
await Promise.all(promises);
});
}
this.createChannel = async function() {
while (!this.connection) {
await sleep(100);
}
return await this.connection.createChannel();
}
this.onClose = function (handler) {
const handlerId = uuidv4();
this.onCloseHandler[handlerId] = handler;
return handlerId;
}
this.removeOnCloseHandler = function(handlerId) {
delete this.onCloseHandler[handlerId];
}
async function createConnection(connectionString) {
while (true) {
try {
return await amqplib.connect(connectionString);
} catch (e) {
console.log(e);
await sleep(500);
}
}
}
}
async function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}