Skip to content

Commit

Permalink
request/response framework in websocket
Browse files Browse the repository at this point in the history
  • Loading branch information
lideming committed Apr 12, 2022
1 parent 0d50879 commit 99a6769
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/Client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,14 @@ export class Client {
}

private handleNewData(parsed: any) {
if (parsed.requestId) {
const callback = this.requestCallbacks[parsed.requestId];
if (callback) {
callback(parsed);
delete this.requestCallbacks[parsed.requestId];
}
return;
}
for (const key in parsed) {
if (Object.prototype.hasOwnProperty.call(parsed, key)) {
const val = parsed[key];
Expand All @@ -105,6 +113,17 @@ export class Client {
this.send(JSON.stringify(jsonObj));
}

lastRequestId = 0;
requestCallbacks: Record<number, (obj: object) => void> = {};

request(obj: object) {
const id = ++this.lastRequestId;
this.sendJson({requestId: id, ...obj});
return new Promise<object>((resolve) => {
this.requestCallbacks[id] = resolve;
});
}

close() {
this.reconnectTimer.tryCancel();
if (this.closed) return;
Expand Down

0 comments on commit 99a6769

Please sign in to comment.