Skip to content

Commit e0e7007

Browse files
committed
Enhanced hub
Signed-off-by: Vishal Rana <[email protected]>
1 parent ec204c7 commit e0e7007

File tree

2 files changed

+22
-7
lines changed

2 files changed

+22
-7
lines changed

lib/hub.js

+21-6
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,19 @@
11
const mqtt = require('mqtt')
22

33
class Hub {
4-
constructor(accountID, apiKey, clientID) {
4+
constructor(accountID, apiKey, options) {
55
this.accountID = accountID
66
this.apiKey = apiKey
77
this.handlers = {}
8+
this.options = options || {}
9+
}
10+
11+
_normalizeTopic(topic) {
12+
return `${this.accountID}/${topic}`
13+
}
14+
15+
_denormalizeTopic(topic) {
16+
return topic.replace(this.accountID + '/', '');
817
}
918

1019
connect(handler) {
@@ -18,24 +27,30 @@ class Hub {
1827
}
1928
})
2029
this.client.on('message', (topic, message) => {
21-
this.handlers[topic](message)
30+
topic = this._denormalizeTopic(topic)
31+
handler = this.handlers[topic]
32+
if (this.options.messageHandler) {
33+
this.options.messageHandler(topic, message)
34+
}
35+
if (handler) {
36+
handler(topic, message)
37+
}
2238
})
2339
// this.client.on('end', () => {
2440
// })
2541
}
2642

2743
publish(topic, message) {
28-
this.client.publish(`${this.accountID}/${topic}`, message)
44+
this.client.publish(this._normalizeTopic(topic), message)
2945
}
3046

3147
subscribe(topic, handler) {
32-
topic = `${this.accountID}/${topic}`
33-
this.client.subscribe(topic)
48+
this.client.subscribe(this._normalizeTopic(topic))
3449
this.handlers[topic] = handler
3550
}
3651

3752
unsubscribe(self, topic) {
38-
this.client.unsubscribe(`${this.accountID}/${topic}`)
53+
this.client.unsubscribe(this._normalizeTopic(topic))
3954
}
4055

4156
disconnect(self) {

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "labstack",
3-
"version": "0.31.8",
3+
"version": "0.32.0",
44
"description": "Official Node.js client library for the LabStack platform",
55
"main": "index.js",
66
"scripts": {

0 commit comments

Comments
 (0)