Skip to content

Single connection #8

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jan 8, 2019
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Clean up subscribed topics upon disconnect
  • Loading branch information
xowor committed Dec 19, 2018
commit 223e24b2af776f029e4e2ee790d5b820b8088168
24 changes: 13 additions & 11 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -142,13 +142,13 @@ const connect = options => new Promise((resolve, reject) => {
// connection loss
Object.getOwnPropertySymbols(subscribedTopics).forEach((connectionId) => {
Object.values(subscribedTopics[connectionId]).forEach((subscribeParams) => {
subscribe(connectionId, subscribeParams.topic, subscribeParams.cb)
subscribe(connectionId, subscribeParams.topic, subscribeParams.cb);
});
});
}

if (typeof opts.onConnected === 'function') {
opts.onConnected(reconnect)
opts.onConnected(reconnect);
}
};

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

client.disconnect();
try {
client.disconnect();
} catch (error) {
return reject(error);
}

// Remove the connection
delete connections[id];

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

// Clean up subscribed topics - a new connection might not need the same topics
Object.keys(subscribedTopics).forEach((topic) => {
if (subscribedTopics[topic]) {
delete subscribedTopics[topic];
}
});

delete subscribedTopics[id];
return resolve();
});

const subscribe = (id, topic, cb) => new Promise((resolve, reject) => {
const client = connections[id];
if (!client) {
return reject(new Error('disconnection failed: client not found'));
return reject(new Error('subscription failed: client not found'));
}

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

subscribedTopics[connectionId][thingId] = {
topic: propOutputTopic,
cb: cb,
cb,
};

if (!propertyCallback[propOutputTopic]) {
Expand Down