CometD client for Node.js that adds support for promises
Installation
Add the client to your project by running:
npm install cometd-node-promise-client
Usage
- Instantiate the CometD client
1.a) with the default console logger:
const cometd = new CometdClient();
OR
1.b) with the Winston logger:
Winston.loggers.add('COMETD', {
console: { level: 'info', colorize: true, label: 'COMETD' }
});
const cometd = new CometdClient(Winston.loggers.get('COMETD'));
- Configure the CometD client
cometd.configure({
url: cometdServerUrl,
requestHeaders: { Authorization: 'Bearer ' + this.session.access_token },
appendMessageTypeToURL: false
});
- Handshake with the CometD server and subscribe to a
topicName
topic:
cometd.connect().then(() => {
cometd.subscribe(topicName, onMessageReceived).then(subscription => {
});
});
The onMessageReceived
callback function is executed each time a topicName
message is received.
Alternatively, you can batch subscriptions (network optimization):
const cometdPromises = [
cometd.subscribe(topic1, onMessage1Received),
cometd.subscribe(topic2, onMessage2Received)
];
cometd.batch(cometdPromises).then(() => {
});
- If you wish to unsubscribe from a topic:
cometd.unsubscribe(subscription).then(() => {
});
- When you no longer need your CometD client, disconnect from the server:
cometd.disconnect().then(() => {
});
disconnect()
unsubscribes from all active subscriptions.