Add autoRemove functionality for api.subscribe

This commit is contained in:
Jaco Greeff 2016-12-09 00:00:56 +01:00
parent 2d6656fc43
commit ad971a444c

View File

@ -59,7 +59,7 @@ export default class Manager {
return subscription; return subscription;
} }
subscribe (subscriptionName, callback) { subscribe (subscriptionName, callback, autoRemove = false) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const subscription = this._validateType(subscriptionName); const subscription = this._validateType(subscriptionName);
@ -75,6 +75,7 @@ export default class Manager {
this.subscriptions[subscriptionId] = { this.subscriptions[subscriptionId] = {
name: subscriptionName, name: subscriptionName,
id: subscriptionId, id: subscriptionId,
autoRemove,
callback callback
}; };
@ -104,13 +105,16 @@ export default class Manager {
const { callback } = this.subscriptions[subscriptionId]; const { callback } = this.subscriptions[subscriptionId];
try { try {
callback(error, data); return callback(error, data);
} catch (error) { } catch (error) {
console.error(`Unable to update callback for subscriptionId ${subscriptionId}`, error); console.error(`Unable to update callback for subscriptionId ${subscriptionId}`, error);
} }
return true;
} }
_updateSubscriptions = (subscriptionName, error, data) => { _updateSubscriptions = (subscriptionName, error, data) => {
const cleanup = [];
const subscriptions = this.subscriptions const subscriptions = this.subscriptions
.filter(subscription => subscription.name === subscriptionName); .filter(subscription => subscription.name === subscriptionName);
@ -118,7 +122,15 @@ export default class Manager {
subscriptions subscriptions
.forEach((subscription) => { .forEach((subscription) => {
this._sendData(subscription.id, error, data); const result = this._sendData(subscription.id, error, data);
if (subscription.autoRemove && !result) {
cleanup.push(subscription.id);
}
});
cleanup.forEach((subscriptionId) => {
delete this.subscriptions[subscriptionId];
}); });
} }
} }