Skip to content

Commit

Permalink
added subscription
Browse files Browse the repository at this point in the history
  • Loading branch information
Egge21M committed Mar 28, 2024
1 parent f583b78 commit e6e18eb
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion src/WSConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,19 @@ export function injectWebSocketImpl(ws: any) {
_WS = ws;
}

class Subscription {
private connection: WSConnection;
private subId: string;
constructor(conn: WSConnection) {
// HACK: There might be way better ways to create an random string, but I want to create something without dependecies frist
this.subId = Math.random().toString(36).slice(-5);
this.connection = conn;
}
onmessage(cb: () => any) {
this.connection.addListener(this.subId, cb);
}
}

export class WSConnection {
public readonly url: URL;
private ws: WebSocket | undefined;
Expand Down Expand Up @@ -49,6 +62,12 @@ export class WSConnection {
(this.listeners[subId] = this.listeners[subId] || []).filter((fn) => fn !== callback);
}

async ensureConenction() {
if (this.ws?.readyState !== 1) {
await this.connect();
}
}

handleNextMesage() {
if (this.messageQueue.size === 0) {
clearInterval(this.handlingInterval);
Expand Down Expand Up @@ -80,6 +99,9 @@ export class WSConnection {
return;
}
}
const len = parsed.length;
}

subscribe() {
return new Subscription(this);
}
}

0 comments on commit e6e18eb

Please sign in to comment.