-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.ts
57 lines (50 loc) · 1.52 KB
/
client.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { parseMessage, sendMessage } from "./messages.ts";
import { RPCClientOptions, RPCReply, RPCService } from "./types.ts";
export async function initializeClient<
Contracts extends Record<string, RPCService>,
>(
options: RPCClientOptions,
): Promise<Contracts> {
const ws = new WebSocket(options.host);
const call = (service: string, ...args: never[]) => {
return new Promise<RPCReply>((resolve) => {
const controller = new AbortController();
const messageId = crypto.randomUUID();
sendMessage(ws, {
id: messageId,
service,
args,
});
ws.addEventListener("message", (event) => {
const data = event.data as string;
const message = parseMessage(data) as RPCReply;
if (message.id !== messageId) return;
controller.abort();
resolve(message);
}, { signal: controller.signal });
});
};
const callService = (service: string) => {
return (...args: never[]) => {
return call(service, ...args);
};
};
const proxyHandler: ProxyHandler<Record<string, RPCService>> = {
get: (target, name: string) => {
if (name === "then") {
return target[name];
}
return Object.prototype.hasOwnProperty.call(target, name)
? target[name]
: callService(name);
},
};
// deno-lint-ignore no-explicit-any
const proxy = new Proxy({ call } as any, proxyHandler);
await new Promise<void>((resolve) => {
ws.onopen = (_ev) => {
resolve();
};
});
return proxy as Contracts;
}