Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use promisified smqp as backend #5

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .nvmrc
Original file line number Diff line number Diff line change
@@ -1 +1 @@
8
10
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
language: node_js
node_js:
- 8
- 9
- 10
- 12
sudo: false
186 changes: 99 additions & 87 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,104 +1,116 @@
"use strict";

let exchanges = {};
let queues = {};
const {Broker} = require("smqp");

module.exports = {connect, resetMock};
const connections = [];

function connect(url, options, connCallback) {
if (!connCallback) {
options = {};
connCallback = options;
}
module.exports = Fake();

const connection = {
createChannel: createChannel(false),
createConfirmChannel: createChannel(true),
on: function () {},
close: resetMock,
function Fake() {
return {
connections,
resetMock,
connect,
};

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 connect(amqpUrl, ...args) {
const {_broker} = connections.find((conn) => conn.options[0] === amqpUrl) || {};
const broker = _broker || Broker();
const connection = Connection(broker, amqpUrl, ...args);
connections.push(connection);
return resolveOrCallback(args.slice(-1)[0], null, connection);
}

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 resetMock() {
for (const connection of connections.slice()) {
connection.close();
}
}

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 Connection(broker, ...connArgs) {
const options = connArgs.filter((a) => typeof a !== "function");

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;
}
return {
_broker: broker,
options,
createChannel(...args) {
return resolveOrCallback(args.slice(-1)[0], null, Channel(broker));
},
createConfirmChannel(...args) {
return resolveOrCallback(args.slice(-1)[0], null, Channel(broker, true));
},
close(...args) {
const idx = connections.indexOf(this);
if (idx > -1) connections.splice(idx, 1);
broker.reset();
return resolveOrCallback(args.slice(-1)[0]);
},
on() {},
};
}

function consume(queue, handler) {
queues[queue].subscribers.push(handler);
}
function Channel(broker, confirm) {
return {
assertExchange(...args) {
return callBroker(broker.assertExchange, ...args);
},
assertQueue(...args) {
return callBroker(broker.assertQueue, ...args);
},
bindQueue(...args) {
return callBroker(broker.bindQueue, ...args);
},
deleteQueue(...args) {
return callBroker(broker.deleteQueue, ...args);
},
publish(exchange, routingKey, content, ...args) {
if (!Buffer.isBuffer(content)) throw new TypeError("content is not a buffer");
return confirm ? callBroker(broker.publish, exchange, routingKey, content, ...args) : broker.publish(exchange, routingKey, content, ...args);
},
sendToQueue(queue, content, ...args) {
if (!Buffer.isBuffer(content)) throw new TypeError("content is not a buffer");
return confirm ? callBroker(broker.sendToQueue, queue, content, ...args) : broker.sendToQueue(queue, content, ...args);
},
consume(queue, onMessage, ...args) {
const passArgs = args.length ? args : [{}];
return callBroker(broker.consume, queue, onMessage && handler, ...passArgs);
function handler(_, msg) {
onMessage(msg);
}
},
cancel(...args) {
return callBroker(broker.cancel, ...args);
},
ack: broker.ack,
ackAll: broker.ackAll,
nack: broker.nack,
reject: broker.reject,
nackAll: broker.nackAll,
prefetch() {},
on: broker.on,
};

function deleteQueue(queue) {
setImmediate(() => {
delete queues[queue];
});
}
function callBroker(fn, ...args) {
let [poppedCb] = args.slice(-1);
if (typeof poppedCb === "function") args.splice(-1);
else poppedCb = null;

function ack() {}
function nack() {}
function prefetch() {}
function on() {}
};
return new Promise((resolve, reject) => {
try {
const result = fn(...args);
if (poppedCb) poppedCb(null, result);
return resolve(result);
} catch (err) {
if (!poppedCb) return reject(err);
poppedCb(err);
return resolve();
}
});
}
}
}

function resetMock() {
queues = {};
exchanges = {};
}

function setIfUndef(object, prop, value) {
if (!object[prop]) {
object[prop] = value;
}
function resolveOrCallback(optionalCb, err, ...args) {
if (typeof optionalCb === "function") optionalCb(err, ...args);
return Promise.resolve(...args);
}
Loading