diff --git a/client_js/CHANGELOG.md b/client_js/CHANGELOG.md index ef656f0..fa5493c 100644 --- a/client_js/CHANGELOG.md +++ b/client_js/CHANGELOG.md @@ -1,5 +1,11 @@ # CHANGELOG +## 0.3.1 + +### Features + +- Adds optional `createWebSocket` factory function for customizing WebSocket creation. + ## 0.3.0 ### Features diff --git a/client_js/package.json b/client_js/package.json index 4e5009a..c746869 100644 --- a/client_js/package.json +++ b/client_js/package.json @@ -1,6 +1,6 @@ { "name": "@topical/core", - "version": "0.3.0", + "version": "0.3.1", "description": "Vanilla Topical client.", "main": "dist/index.js", "typings": "dist/index.d.ts", diff --git a/client_js/src/index.ts b/client_js/src/index.ts index ba98b6a..fbb53ff 100644 --- a/client_js/src/index.ts +++ b/client_js/src/index.ts @@ -1 +1,7 @@ -export { default as Socket, Params, ParamsInput, SocketState } from "./socket"; +export { + default as Socket, + Params, + ParamsInput, + SocketState, + WebSocketFactory, +} from "./socket"; diff --git a/client_js/src/socket.ts b/client_js/src/socket.ts index 1794729..6b81766 100644 --- a/client_js/src/socket.ts +++ b/client_js/src/socket.ts @@ -50,6 +50,8 @@ function topicKey(topic: string[], params: Params): string { return `${topic.map(encodeURIComponent).join("/")}?${sortedParams}`; } +export type WebSocketFactory = (url: string) => WebSocket; + export default class Socket { private socket: WebSocket; private closed = false; @@ -61,15 +63,20 @@ export default class Socket { // Maps aliased channel IDs to their target channel IDs private aliases: Record = {}; private listeners: ((state: SocketState) => void)[] = []; + private createWebSocket: WebSocketFactory; - constructor(private readonly url: string) { + constructor( + private readonly url: string, + createWebSocket?: WebSocketFactory, + ) { + this.createWebSocket = createWebSocket ?? ((url) => new WebSocket(url)); this.socket = this.open(); } private open() { this.closed = false; this.setState("connecting"); - const socket = new WebSocket(this.url); + const socket = this.createWebSocket(this.url); socket.addEventListener("open", this.handleSocketOpen); socket.addEventListener("error", this.handleSocketError); socket.addEventListener("message", this.handleSocketMessage);