A promise-based AMQP API build on node-amqp
npm install amqp-as-promisedAMQP as Promised
================
!Version
!License
!Monthly downloads
!Build Status
A high-level promise-based API built onamqplib
extended with functions for AMQP-based RPC.
* [amqplib API docs][amqplib-api-docs]
* Old versions of this package were based on [node-amqp][npm-node-amqp].
[amqplib-api-docs]: http://www.squaremobius.net/amqp.node/channel_api.html
[npm-node-amqp]: https://github.com/postwait/node-amqp
* Configuration
* Examples
* API
* The amqpc object
* The exchange object
* The queue object
* RPC functions
* Changelog
#### 5.0
Syntax to access the library has been changed in 5.0 to improve
connection management. See the Running-section for
instructions.
#### 3.0
The underlying amqp library was changed fromnode-amqp to amqplib. Efforts have been made to keep everything as
backwards compatible as possible, but some things have changed:
* Local mode is no longer supported.
* queue.shift() is no longer supported.
* Q has been dropped in favor of native promises. As a result,
support for promise progress notifications over RPC is no longer
supported.
npm install amqp-as-promised
5.0+
``coffee`
conf = require './myconf.json' # see example conf below
((require 'amqp-as-promised') conf.amqp).then (amqpc) ->
Earlier versions
`coffee`
conf = require './myconf.json' # see example conf below
amqpc = (require 'amqp-as-promised') conf.amqp
As of version 0.1.0, the following config parameters are accepted,
although we also try to keep backwards compatibility with the older
format.
Connection settings accepted by
node-amqp. You
need to at minimum specify either
* hostvhost
* login
* password
*
or
* url.
* timeout: timeout in ms for rpc calls. Default: 1000ms
Since 5.7.0
* publisherConfirm: boolean that enables or disables the RabbitMQ
Publisher Confirms extension.
Default: false.
* logLevel: sets the log level. Defaults to INFO. Possible levelsDEBUG
are , INFO, WARN, ERROR
Since 2.0.0 connection errors are rethrown to crash process.
* errorHandler: sets a handler function to receive the error insteaderror
of throwing to process. This option is deprecated, as a better way to
do this is to attach an event handler.
Since 4.1.0
* waitForConnection: on startup, keeps retrying to connect until
successful. Will not attempt reconnect after established connection.
{
"connection": {
"host": "192.168.0.10",
"vhost": "test",
"login": "test",
"password": "supersecret"
},
"publisherConfirm": true,
"logLevel": "warn",
"rpc": {
"timeout": 2000
}
}
Or with url:
{
"connection": {
"url": "amqp://myuser:supersecret@192.168.0.10/test"
},
"logLevel": "warn"
}
Events
=======
Amqp-as-promised emits error events on unexpected network errors,
for example then the connection to the server has been lost. It is up
to the client to handle these errors, as amqp-as-promised doesn't
reconnect automatically. Keep in mind that error recovery can be
tricky, and the best option might be to just crash and restart the
application on error.
This is a simple but effective error handler:
`coffee`
amqpc.on 'error', (err) ->
console.log err
process.exit 1
If there are no error handlers attached (either using amqp.on() orerrorHandler
setting the in the configuration), amqp-as-promisedprocess
will as a last resort throw the error. This will most likely result in
an application crash unless there is an uncaught exception handler set
on the .
Examples
==========
to publish`coffee`
amqpc.exchange('myexchange').then (ex) ->
msg = {}
msg.domain = domain
ex.publish('mytopic.foo', msg).then ->
console.log 'published message!'
to bindThis is shorthand for binding and subscribing.
`coffee`
amqpc.bind 'myexchange', 'myqueue', 'mytopic.#', (msg, headers, del) ->
console.log 'received message', msg
To bind an anonymous queue.
amqpc.bind 'myexchange', '', 'mytopic.#', (msg, headers, del) ->
console.log 'received message', msg
Or even shorter
`coffee`
amqpc.bind 'myexchange', 'mytopic.#', (msg, headers, del) ->
console.log 'received message', msg
To bind the queue to the exchange without subscribing to it, skip the
last parameter (the subscription callback). This is essentially the
same as queue.bind myexchange, 'mytopic', except the exchange and
queue are specified by their names:
`coffee`
amqpc.bind 'myexchange', 'myqueue', 'mytopic.#'
to get an anomymous queueTo create an anomymous queue.
`coffee`
amqpc.queue().then (q) -> console.log 'my queue', q
to do RPC-style callsto send a message to a service that honors the replyTo/correlationId contract:
`coffee`
amqpc.rpc('myexchange', 'routing.key', msg, [headers], [options]).then (response) ->
console.log 'received message', response
* headers is an optional parameter holding any custom headers to beoptions
passed on the RPC service.
* supports the following settingstimeout
- - the timeout in ms for this call
Note! In earlier versions the response was an array that included
the response headers. As of version 0.1.0, this is no longer the case.
to serve RPC-style callsTo set up a message consumer that automatically honors the
replyTo/correlationId contract:
`coffee`
amqpc.serve 'myexchange', 'mytopic.#', (msg, headers, del) ->
return { result: 'ok' }
The value returned from the handler will be sent back on the queue
specified by the replyTo header, with the correlationId set.
If an exception is thrown by the handler, it will be propagated back
to the client as an object:
``
{
"error": {
"message":
[ "code":
[ "errno":
}
}
To rate limit the rpc calls to 5 concurrent, we use an options object
to set {ack:true, prefetchCount:5}.
Notice that the message acking is handled by the rpc backend wrapper.
`coffee`
amqpc.serve 'myexchange', 'mytopic.#', {ack:true, prefetchCount:5}, (msg, headers, del) ->
return { result: 'ok' }
`coffee
graceful = (opts) ->
log.info 'Shutting down'
amqpc.shutdown().then ->
process.exit 0
process.on 'SIGINT', graceful
process.on 'SIGTERM', graceful
`
API
===
objectAttach an event handler. Currently only error events are supported.
A promise for an exchange. If opts is omitted, then passive:true
is assumed.
A promise for a queue. If qname is omitted, "" is used. If opts isexclusive:true
omitted, then is assumed if the name is empty, orpassive:true if not.
Thus, amqpc.queue() will create a new exclusive, anonymous, queueamqpc.queue('my-queue')
that is automatically deleted on disconnect, while will try to passively declare the existingmy-queue
queue .
See queue.* below.
Shorthand for
1. If exchange is a string, then look up the existing exchange withqueue
that name.
2. If is a string, then look up the existing queue with that name.exchange/topic
3. Bind queue to .callback
4. Subscribe to queue (optional).
#### Parameters
* exchange - an exchange object or a string with the name of anqueue
exchange
* - a queue object or a string with the name of a queuetopic
* - a string with the topic name.callback
* - see queue.subscribe below.
Will unbind all queues and unsubscribe all callbacks then gracefully
shut down the socket connection.
objectPublishes a message, returning a promise.
objectBinds the queue to the given exchange (object, or string). Will unbind
if queue was already bound.
Unbinds the queue (if currently bound).
Subscribes the callback to this queue. Will unsubscribe any previous
callback. If opts is omitted, defaults to ack: false, prefetchCount: 1
The callback will be called with arguments (msg, headers, deliveryinfo,
actions), where actions is an object that holds these methods:
* acknowledge(): returns a Promise to acknowledge the message. This isopts.ack
only relevant if is false (which is the default).
Unsubscribes current callback (if any).
Read only property with the queue name.
Perform an AMQP-based remote procedure call, and returns a promise for
the return value:
1. Creates an exlusive, anonymous, return queue if doesn't already
exist.
2. Publishes an RPC-style message on the given exchange, with theroutingkey
specified , headers and options. The replyTo andcorrelationId
headers are set automatically.error
3. Waits for a reply on the return queue, and resolves the promise
with the contents of the reply. If no reply is received before the
timeout, the promise is instead rejected. Replies that are JSON
objects that have an property set are assumed to be remote
errors, and will result in a rejected promise.
#### Parameters
* exchange - the name of an exchange, or an exchange objectroutingkey
* headers
* - AMQP headers to be sent with the message. See exchange.publish().options
* - valid options are:timeout
+ - timeout in milliseconds. If none is specified, thecompress
default value specified when creating the client is used.
+ - set to true to use payload compression
Since 0.4.0
The RPC mechanism has a transparent payload gzip compression of JSON
objects Buffer. When activated both request and response are
compressed. To activate, the rpc client must ask for compression by setting
the compress option.
Example
`coffee``
amqpc.rpc('myexchange', 'routing.key', msg, [headers], {compress:true}).then (response) ->
console.log 'received message', response