Skip to content

Commit 7bc5092

Browse files
committed
Add SocketStream#factory
1 parent 40bdbd4 commit 7bc5092

File tree

1 file changed

+10
-8
lines changed

1 file changed

+10
-8
lines changed

packages/polling/src/socketstream.ts

+10-8
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,9 @@ export class SocketStream<T, U> extends Stream<T, U> implements IDisposable {
2424
*
2525
* @param options = The socket stream instantiation options.
2626
*/
27-
constructor(
28-
sender: T,
29-
protected readonly options: SocketStream.IOptions
30-
) {
27+
constructor(sender: T, options: SocketStream.IOptions) {
3128
super(sender);
29+
this.factory = () => new (options.WebSocket || WebSocket)(options.url);
3230
this.subscription = new Poll({ factory: () => this.subscribe() });
3331
}
3432

@@ -66,6 +64,11 @@ export class SocketStream<T, U> extends Stream<T, U> implements IDisposable {
6664
this.socket?.send(data);
6765
}
6866

67+
/**
68+
* A factory that generates a new web socket instance for subscription.
69+
*/
70+
protected readonly factory: () => WebSocket;
71+
6972
/**
7073
* The current active socket. This value is updated by the `subscribe` method.
7174
*/
@@ -86,10 +89,9 @@ export class SocketStream<T, U> extends Stream<T, U> implements IDisposable {
8689
return;
8790
}
8891
return new Promise<void>((_, reject) => {
89-
const Socket = this.options.WebSocket || WebSocket;
90-
const socket = (this.socket = new Socket(this.options.url));
91-
socket.onclose = () => reject(new Error('socket stream: socket closed'));
92-
socket.onmessage = msg => msg.data && this.emit(JSON.parse(msg.data));
92+
this.socket = this.factory();
93+
this.socket.onclose = () => reject(new Error('socket stream has closed'));
94+
this.socket.onmessage = ({ data }) => data && this.emit(JSON.parse(data));
9395
});
9496
}
9597
}

0 commit comments

Comments
 (0)