11const mqtt = require ( 'mqtt' )
22
33class Hub {
4- constructor ( accountID , apiKey , clientID ) {
4+ constructor ( accountID , apiKey , options ) {
55this . accountID = accountID
66this . apiKey = apiKey
77this . 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
1019connect ( handler ) {
@@ -18,24 +27,30 @@ class Hub {
1827}
1928} )
2029this . 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
2743publish ( topic , message ) {
28- this . client . publish ( ` ${ this . accountID } / ${ topic } ` , message )
44+ this . client . publish ( this . _normalizeTopic ( topic ) , message )
2945}
3046
3147subscribe ( topic , handler ) {
32- topic = `${ this . accountID } /${ topic } `
33- this . client . subscribe ( topic )
48+ this . client . subscribe ( this . _normalizeTopic ( topic ) )
3449this . handlers [ topic ] = handler
3550}
3651
3752unsubscribe ( self , topic ) {
38- this . client . unsubscribe ( ` ${ this . accountID } / ${ topic } ` )
53+ this . client . unsubscribe ( this . _normalizeTopic ( topic ) )
3954}
4055
4156disconnect ( self ) {