NATS Wrapper for JavaScript
A wrapper over node-nats, designed to meet the needs of ISAAX project.
Installation
npm install xshellinc/isaax-nats-js-wrapper#v2.1.2 --save
Usage
Create an instance of the wrapper:
import NATSWrapper from 'isaax-nats-js-wrapper';
const nats = new NATSWrapper({group: 'some-service'});
nats.on('connect', () => {
// wrapper is ready at this point
});
nats.on('error', () => {
process.exit(1); // error message will be logged before exiting
});
Publish a request and get a response in callback:
nats.request('some.package', {type: 'ordinary'}, (error, package) => {
console.log(error, package)
});
Note: this method uses requestOne
inside, no need to worry about max responses
Subscribe and respond to a request:
nats.listen('some.request', ({id}, respond) => {
someModule.fetch(id, (error, pack) => {
respond(error, pack);
});
});
Note: a listener is automatically added to queue group some.request.listeners
Publish an event:
nats.publish('some.package.sent', pack);
Subscribe and process as worker queue:
nats.process('*.package.sent', (pack, subject) => {
console.log(subject, pack);
});
listen
, subscribe
and process
methods return an integer subscription ID (SID) which can be used to unsubscribe from a subject:
const sid = nats.process('*.package.sent', (pack, subject) => {
console.log(subject, pack);
});
// ...
nats.unsubscribe(sid);
Close NATS connection (if needed):
nats.close();
Environment variables
NATS_LOG_LEVEL
- set wrapper's log level. Default isdebug