-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprovider.js
97 lines (88 loc) · 2.79 KB
/
provider.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
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
class Provider {
constructor(options) {
this.amqp = require("amqplib");
this.queue = options.queue || "";
this.channel = null;
this.correlationId = options.correlationId;
this.connectionAdress = options.connectionAdress || null;
this.connection = null;
this.contentType = options.contentType
? options.contentType == "application/json"
? "application/json"
: "application/textplain"
: "application/textplain";
this.responseType = options.contentType
? options.contentType == "application/json"
? "application/json"
: "application/textplain"
: "application/textplain";
this.responseFn = options.responseFn;
}
async connect(connection_adress) {
return this.amqp
.connect(connection_adress)
.then((connection) => {
this.channel = connection.createChannel();
return new Promise((resolve) => resolve(this.channel));
})
.then((channel) => {
this.channel = channel;
return this.channel.assertQueue(this.queue).then(() => {
return this.channel.consume(this.queue, async (msg) => {
var message;
if (msg !== null) {
const isJson = (str) => {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
};
message = isJson(
(message = Buffer.from(
JSON.stringify(msg.content.toString("utf8"))
).toJSON())
)
? (message = Buffer.from(
JSON.stringify(msg.content.toString("utf8"))
).toJSON())
: Buffer.from(msg.content).toString("utf8");
const getResponse = await this.responseFn(
message,
msg.properties.correlationId
);
if (getResponse != undefined) {
this.channel.sendToQueue(
msg.properties.replyTo,
typeof getResponse === "object"
? Buffer.from(JSON.stringify(getResponse))
: Buffer.from(getResponse),
{
correlationId: msg.properties.correlationId,
}
);
this.channel.ack(msg);
}
}
});
});
});
}
}
new Provider({
queue: "example4",
responseFn: async (message, reply) => {
switch (message) {
case "command1":
return "Hi there!"
break;
case "command2":
return {status: 200}
break;
default:
return {result: 404, reason: "not found command."}
break;
}
},
}).connect("amqp://localhost");