-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathevent-emitter-to-async-iterator.js
77 lines (66 loc) · 1.85 KB
/
event-emitter-to-async-iterator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Based on https://github.com/apollographql/graphql-subscriptions/blob/master/src/event-emitter-to-async-iterator.ts
const { $$asyncIterator } = require("iterall");
const { EventEmitter } = require("events");
function eventEmitterAsyncIterator(eventEmitter, eventsNames, commonMessageHandler = message => message) {
const pullQueue = [];
const pushQueue = [];
const eventsArray =
typeof eventsNames === "string" ? [eventsNames] : eventsNames;
let listening = true;
const pushValue = ({ payload: event }) => {
const value = commonMessageHandler(event);
if (pullQueue.length !== 0) {
pullQueue.shift()({ value, done: false });
} else {
pushQueue.push(value);
}
};
const pullValue = () => {
return new Promise(resolve => {
if (pushQueue.length !== 0) {
resolve({ value: pushQueue.shift(), done: false });
} else {
pullQueue.push(resolve);
}
});
};
const emptyQueue = () => {
if (listening) {
listening = false;
removeEventListeners();
pullQueue.forEach(resolve => resolve({ value: undefined, done: true }));
pullQueue.length = 0;
pushQueue.length = 0;
}
};
const addEventListeners = () => {
for (const eventName of eventsArray) {
eventEmitter.addListener(eventName, pushValue);
}
};
const removeEventListeners = () => {
for (const eventName of eventsArray) {
eventEmitter.removeListener(eventName, pushValue);
}
};
addEventListeners();
return {
next() {
return listening ? pullValue() : this.return();
},
return() {
emptyQueue();
return Promise.resolve({ value: undefined, done: true });
},
throw(error) {
emptyQueue();
return Promise.reject(error);
},
[$$asyncIterator]() {
return this;
}
};
}
module.exports = {
eventEmitterAsyncIterator
};