amq-broker
v0.0.4
Published
## Installation
Downloads
2
Readme
amq-broker
Installation
$ npm install amq-broker --save
Usage
Set up process variable CLOUDAMQP_URL or AMQP_URL pointing to the broker instance.
//module will lookup process variable and establish connection
const msgBroker = require("amq-broker");
//get the handle to Events construct
const Events = msgBroker.Events;
//Publish directly to an exchange named 'notify' with routing key 'create'
msgBroker.publish("notify", "createx", Events.simple({ name: "tx" }));
//Publish directly to a queue
msgBroker.sendToQueue(
"transaction",
Events.simple({ source: "shopify", id: "12345", amount: "45 SGD" })
);
//Consume directly from a queue
msgBroker.consume("transaction", (response) =>
console.log("Recieved response : " + response)
);
//To release connections on exit, set up closeonExit with an optional handler
//Once the process terminate, connections will be released and the optional handler will be invoked
msgBroker.closeOnExit((err, success) => {
if (err) {
console.error("Error while releasing MQ connections", err);
return;
}
console.log("Successfully released MQ connections");
});
Events
Events are data wrappers. Currently supports "simple" and "chained".
const msgBroker = require("sg-lab-broker");
//get the handle to Events construct
const Events = msgBroker.Events;
//create a simple event
let shopping = { source: "txn", id: "Tx1245", amount: "10 SGD" };
//wrap that in event using simple construct
let simpleEvent = Events.simple(shopping);
//create one more data
let sms = { to: "+3111", message: "Hello World!!" };
//lets create a chained event
let chainedEvent = Events.chained()
.add("txn", shopping) //add shopping to the chain
.add("sms", sms) //add sms also to the chain
.build();
//Events construct helps to retrieve data within consumers
let smsData = Events.getData(chainedEvent, "sms");
//or
let shoppingData = Events.getData(simpleEvent);
Queue operations
//create a queue named 'queue-name'
msgBroker
.createQueue("queue-name", {})
.then((data) => console.log(data))
.catch((error) => console.log(error));
//bind the queue, 'queue-name' to the exchange, 'exchange-name' using topic, '#.routing-key.#'
// #.routing-key.# means match any message which it's topic contains the string '.routing-key.'
msgBroker
.bindQueue("queue-name", "exchange-name", '"#.routing-key.#')
.then((data) => console.log(data))
.catch((error) => console.log(error));
//unbind the queue, 'queue-name' for the topic, '#.routing-key.#' from the exchange, 'exchange-name'
msgBroker
.unbindQueue("queue-name", "exchange-name", '"#.routing-key.#')
.then((data) => console.log(data))
.catch((error) => console.log(error));
//delete the queue named 'queue-name'
msgBroker
.deleteQueue("queue-name", {})
.then((data) => console.log(data))
.catch((error) => console.log(error));