graphql-redis-subscriptions
Version:
A graphql-subscriptions PubSub Engine using redis
70 lines • 2.29 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PubSubAsyncIterator = void 0;
class PubSubAsyncIterator {
constructor(pubsub, eventNames, options) {
this.pubsub = pubsub;
this.options = options;
this.pullQueue = [];
this.pushQueue = [];
this.listening = true;
this.eventsArray = typeof eventNames === 'string' ? [eventNames] : eventNames;
}
async next() {
await this.subscribeAll();
return this.listening ? this.pullValue() : this.return();
}
async return() {
await this.emptyQueue();
return { value: undefined, done: true };
}
async throw(error) {
await this.emptyQueue();
return Promise.reject(error);
}
[Symbol.asyncIterator]() {
return this;
}
async pushValue(event) {
await this.subscribeAll();
if (this.pullQueue.length !== 0) {
this.pullQueue.shift()({ value: event, done: false });
}
else {
this.pushQueue.push(event);
}
}
pullValue() {
return new Promise(resolve => {
if (this.pushQueue.length !== 0) {
resolve({ value: this.pushQueue.shift(), done: false });
}
else {
this.pullQueue.push(resolve);
}
});
}
async emptyQueue() {
if (this.listening) {
this.listening = false;
if (this.subscriptionIds)
this.unsubscribeAll(await this.subscriptionIds);
this.pullQueue.forEach(resolve => resolve({ value: undefined, done: true }));
this.pullQueue.length = 0;
this.pushQueue.length = 0;
}
}
subscribeAll() {
if (!this.subscriptionIds) {
this.subscriptionIds = Promise.all(this.eventsArray.map(eventName => this.pubsub.subscribe(eventName, this.pushValue.bind(this), this.options)));
}
return this.subscriptionIds;
}
unsubscribeAll(subscriptionIds) {
for (const subscriptionId of subscriptionIds) {
this.pubsub.unsubscribe(subscriptionId);
}
}
}
exports.PubSubAsyncIterator = PubSubAsyncIterator;
//# sourceMappingURL=pubsub-async-iterator.js.map