Skip to content

Commit 223e24b

Browse files
committed
Clean up subscribed topics upon disconnect
1 parent 2fee57d commit 223e24b

File tree

1 file changed

+13
-11
lines changed

1 file changed

+13
-11
lines changed

src/index.js

+13-11
Original file line numberDiff line numberDiff line change
@@ -142,13 +142,13 @@ const connect = options => new Promise((resolve, reject) => {
142142
// connection loss
143143
Object.getOwnPropertySymbols(subscribedTopics).forEach((connectionId) => {
144144
Object.values(subscribedTopics[connectionId]).forEach((subscribeParams) => {
145-
subscribe(connectionId, subscribeParams.topic, subscribeParams.cb)
145+
subscribe(connectionId, subscribeParams.topic, subscribeParams.cb);
146146
});
147147
});
148148
}
149149

150150
if (typeof opts.onConnected === 'function') {
151-
opts.onConnected(reconnect)
151+
opts.onConnected(reconnect);
152152
}
153153
};
154154

@@ -198,7 +198,14 @@ const disconnect = id => new Promise((resolve, reject) => {
198198
return reject(new Error('disconnection failed: client not found'));
199199
}
200200

201-
client.disconnect();
201+
try {
202+
client.disconnect();
203+
} catch (error) {
204+
return reject(error);
205+
}
206+
207+
// Remove the connection
208+
delete connections[id];
202209

203210
// Remove property callbacks to allow resubscribing in a later connect()
204211
Object.keys(propertyCallback).forEach((topic) => {
@@ -208,19 +215,14 @@ const disconnect = id => new Promise((resolve, reject) => {
208215
});
209216

210217
// Clean up subscribed topics - a new connection might not need the same topics
211-
Object.keys(subscribedTopics).forEach((topic) => {
212-
if (subscribedTopics[topic]) {
213-
delete subscribedTopics[topic];
214-
}
215-
});
216-
218+
delete subscribedTopics[id];
217219
return resolve();
218220
});
219221

220222
const subscribe = (id, topic, cb) => new Promise((resolve, reject) => {
221223
const client = connections[id];
222224
if (!client) {
223-
return reject(new Error('disconnection failed: client not found'));
225+
return reject(new Error('subscription failed: client not found'));
224226
}
225227

226228
return client.subscribe(topic, {
@@ -385,7 +387,7 @@ const onPropertyValue = (connectionId, thingId, name, cb) => {
385387

386388
subscribedTopics[connectionId][thingId] = {
387389
topic: propOutputTopic,
388-
cb: cb,
390+
cb,
389391
};
390392

391393
if (!propertyCallback[propOutputTopic]) {

0 commit comments

Comments
 (0)