1
1
const mqtt = require ( 'mqtt' )
2
2
3
3
class Hub {
4
- constructor ( accountID , apiKey , clientID ) {
4
+ constructor ( accountID , apiKey , options ) {
5
5
this . accountID = accountID
6
6
this . apiKey = apiKey
7
7
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 + '/' , '' ) ;
8
17
}
9
18
10
19
connect ( handler ) {
@@ -18,24 +27,30 @@ class Hub {
18
27
}
19
28
} )
20
29
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
+ }
22
38
} )
23
39
// this.client.on('end', () => {
24
40
// })
25
41
}
26
42
27
43
publish ( topic , message ) {
28
- this . client . publish ( ` ${ this . accountID } / ${ topic } ` , message )
44
+ this . client . publish ( this . _normalizeTopic ( topic ) , message )
29
45
}
30
46
31
47
subscribe ( topic , handler ) {
32
- topic = `${ this . accountID } /${ topic } `
33
- this . client . subscribe ( topic )
48
+ this . client . subscribe ( this . _normalizeTopic ( topic ) )
34
49
this . handlers [ topic ] = handler
35
50
}
36
51
37
52
unsubscribe ( self , topic ) {
38
- this . client . unsubscribe ( ` ${ this . accountID } / ${ topic } ` )
53
+ this . client . unsubscribe ( this . _normalizeTopic ( topic ) )
39
54
}
40
55
41
56
disconnect ( self ) {
0 commit comments