简体   繁体   中英

Publish/Subscribe API design : Unsubscribe and Update

I was looking for a Publication/Subscription system that lets me modify a current subscription. I couldn't find any, so I figured I would build my own (in JavaScript).

I have basic methods for publish and subscribe as follow :

ps.publish(params, function(err, res) {
...
});

ps.subscribe(params, function(err, data) {
...
});

Now I want to add methods for unsubscribing and update ing my subscriptions. Ie. if subscribe is CREATE, then unsubscribe would be DELETE and update would be PUT.

How should I design these APIs ? Should update just be an unsubscribe followed by another subscribe ? How do I let the user choose which subscription ?

Also, I am planning to use the return value to return a future , since I find it a more elegant way to combine asynchronous calls, but I am not sure if this is the best option, I am still weighting it against a fluent API. For that reason, and unless I can choose clearly, I prefer not to use it for now.

unsubscribe seems to be the easy one, but I don't want to end up in the wrong place :

ps.subscribe(params, function(err, data) {
   ps.unsubscribe(data.id);
});

How should I structure these methods ?

Usually subscribe function returns another function which you use to unsubscribe. You could return from subscribe a function which when called without any argument would unsubscribe, but when called with another function as an argument, would update subscription.

In code it would look like this.

ps.subscribe = function (params, callback) {
  ...
  return function (callback) {
    if (callback) {
      ...
      // update - replace with a new callback 
    } else {
      ...
      // cancel subscription
    }
  }
}

var changeSubscription = ps.subscribe(params, callback);
changeSubscription(anotherCallback); // update
changeSubscription(); // unsubscribe

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM