@@ -7,11 +7,29 @@ import type {
7
7
Unsubscribe ,
8
8
} from "@waku/interfaces" ;
9
9
10
+ type IteratorOptions = {
11
+ timeoutMs ?: number ;
12
+ iteratorDelay ?: number ;
13
+ } ;
14
+
15
+ const FRAME_RATE = 60 ;
16
+
17
+ /**
18
+ * Function that transforms IReceiver subscription to iterable stream of data.
19
+ * @param receiver - object that allows to be subscribed to;
20
+ * @param decoder - parameter to be passed to receiver for subscription;
21
+ * @param options - options for receiver for subscription;
22
+ * @param iteratorOptions - optional configuration for iterator;
23
+ * @returns iterator and stop function to terminate it.
24
+ */
10
25
export async function toAsyncIterator < T extends IDecodedMessage > (
11
26
receiver : IReceiver ,
12
27
decoder : IDecoder < T > | IDecoder < T > [ ] ,
13
- options ?: ProtocolOptions
28
+ options ?: ProtocolOptions ,
29
+ iteratorOptions ?: IteratorOptions
14
30
) : Promise < IAsyncIterator < T > > {
31
+ const iteratorDelay = iteratorOptions ?. iteratorDelay ?? FRAME_RATE ;
32
+
15
33
const messages : T [ ] = [ ] ;
16
34
17
35
let unsubscribe : undefined | Unsubscribe ;
@@ -23,8 +41,18 @@ export async function toAsyncIterator<T extends IDecodedMessage>(
23
41
options
24
42
) ;
25
43
44
+ const isWithTimeout = Number . isInteger ( iteratorOptions ?. timeoutMs ) ;
45
+ const timeoutMs = iteratorOptions ?. timeoutMs ?? 0 ;
46
+ const startTime = Date . now ( ) ;
47
+
26
48
async function * iterator ( ) : AsyncIterator < T > {
27
49
while ( true ) {
50
+ if ( isWithTimeout && Date . now ( ) - startTime >= timeoutMs ) {
51
+ return ;
52
+ }
53
+
54
+ await wait ( iteratorDelay ) ;
55
+
28
56
const message = messages . shift ( ) as T ;
29
57
30
58
if ( ! unsubscribe && messages . length === 0 ) {
@@ -49,3 +77,9 @@ export async function toAsyncIterator<T extends IDecodedMessage>(
49
77
} ,
50
78
} ;
51
79
}
80
+
81
+ function wait ( ms : number ) : Promise < void > {
82
+ return new Promise ( ( resolve ) => {
83
+ setTimeout ( resolve , ms ) ;
84
+ } ) ;
85
+ }
0 commit comments