https://github.com/strml/subscription-dedupe
Simple module for reference-counting topic subscriptions
https://github.com/strml/subscription-dedupe
Last synced: 10 months ago
JSON representation
Simple module for reference-counting topic subscriptions
- Host: GitHub
- URL: https://github.com/strml/subscription-dedupe
- Owner: STRML
- Created: 2017-10-02T03:23:30.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2022-03-24T01:49:32.000Z (about 4 years ago)
- Last Synced: 2025-06-10T15:15:34.741Z (10 months ago)
- Language: JavaScript
- Size: 219 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 4
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Subscription-Dedupe
A simple module for reference-counting subscriptions and delegating to a handler.
### Usage
This simple example shows how to dedupe subscriptions to Redis.
When creating a `SubscriptionDedupe`, you must define two methods, `onSubscribe` and `onUnsubscribe`.
If you wish to listen to success/error, you should return a Promise.
```js
const SubscriptionDedupe = require("subscription-dedupe");
const redis = require('redis');
const Promise = require('bluebird');
const redisClient = redis.createClient({/*...*/});
const psubscribeAsync = Promise.promisify(redisClient.psubscribe, {context: redisClient});
const punsubscribeAsync = Promise.promisify(redisClient.punsubscribe, {context: redisClient});
const deduper = new SubscriptionDedupe({
onSubscribe(topic) {
return psubscribeAsync(topic);
},
onUnsubscribe(topic) {
return punsubscribeAsync(topic);
},
// If `false`, will not print to console.warn if your code unsubscribes more
// than it subscribes (which would result in a negative refCount).
// Default `true`
warnOnTooManyUnsubscribes: true,
});
//
// Usage
//
// onSubscribe() called
await deduper.subscribe('topic');
// onSubscribe() NOT called! The original, resolved promise is returned instead.
await deduper.subscribe('topic');
// onUnsubscribe NOT called, as there is still an open subscription.
await deduper.unsubscribe('topic');
// onUnsubscribe() called
await deduper.unsubscribe('topic');
//
// Recovering from errors
//
try {
await deduper.subscribe('topic');
} catch (e) {
// handle error...
// Be sure to unsubscribe - or this will count as a subscription and new attempts will also throw!
// This module doesn't check if the promise threw.
await deduper.unsubscribe('topic');
}
```