-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
104 lines (89 loc) · 2.92 KB
/
index.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
98
99
100
101
102
103
104
"use strict";
let exchanges = {};
let queues = {};
module.exports = {connect, resetMock};
function connect(url, options, connCallback) {
if (!connCallback) {
options = {};
connCallback = options;
}
const connection = {
createChannel: createChannel(false),
createConfirmChannel: createChannel(true),
on: function () {},
close: resetMock,
};
return connCallback(null, connection);
function createChannel(confirm) {
return (channelCallback) => {
channelCallback(null, {
assertQueue,
assertExchange,
bindQueue,
publish,
consume,
deleteQueue,
ack,
nack,
prefetch,
on,
});
function assertQueue(queue, qOptions, qCallback) {
qCallback = qCallback || function () {};
setIfUndef(queues, queue, {messages: [], subscribers: [], options: qOptions});
qCallback();
}
function assertExchange(exchange, type, exchOptions, exchCallback) {
if (typeof (exchOptions) === "function") {
exchCallback = exchOptions;
exchOptions = {};
}
setIfUndef(exchanges, exchange, {bindings: [], options: exchOptions, type: type});
return exchCallback && exchCallback();
}
function bindQueue(queue, exchange, key, args, bindCallback) {
bindCallback = bindCallback || function () {};
if (!exchanges[exchange]) return bindCallback("Bind to non-existing exchange " + exchange);
const re = "^" + key.replace(".", "\\.").replace("#", "(\\S)+").replace("*", "\\w+") + "$";
exchanges[exchange].bindings.push({regex: new RegExp(re), queueName: queue});
bindCallback();
}
function publish(exchange, routingKey, content, props, pubCallback) {
pubCallback = pubCallback || function () {};
if (!exchanges[exchange]) return pubCallback("Publish to non-existing exchange " + exchange);
const bindings = exchanges[exchange].bindings;
const matchingBindings = bindings.filter((b) => b.regex.test(routingKey));
matchingBindings.forEach((binding) => {
const subscribers = queues[binding.queueName] ? queues[binding.queueName].subscribers : [];
subscribers.forEach((sub) => {
const message = {fields: {routingKey: routingKey}, properties: props, content: content};
sub(message);
});
});
if (confirm) pubCallback();
return true;
}
function consume(queue, handler) {
queues[queue].subscribers.push(handler);
}
function deleteQueue(queue) {
setImmediate(() => {
delete queues[queue];
});
}
function ack() {}
function nack() {}
function prefetch() {}
function on() {}
};
}
}
function resetMock() {
queues = {};
exchanges = {};
}
function setIfUndef(object, prop, value) {
if (!object[prop]) {
object[prop] = value;
}
}