-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.ts
47 lines (38 loc) · 1.25 KB
/
server.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
import { sendMessage } from "./messages.ts";
import { parseMessage } from "./messages.ts";
import { RPCMessage, RPCServerOptions } from "./types.ts";
export function initializeServer(options: RPCServerOptions): Deno.HttpServer {
console.log("Initializing WebSocket Server");
const server = Deno.serve({
hostname: "0.0.0.0",
...options,
}, (req) => {
if (req.headers.get("upgrade") != "websocket") {
return new Response(null, { status: 501 });
}
const { socket, response } = Deno.upgradeWebSocket(req);
socket.addEventListener("message", async (event) => {
const message = parseMessage(event.data) as RPCMessage;
const service = options.services.get(message.service);
if (!service) {
return sendMessage(socket, {
id: message.id,
payload: `Service ${message.service} not found!`,
ok: false,
});
}
try {
const response = await service(...message.args);
sendMessage(socket, { id: message.id, payload: response, ok: true });
} catch (error) {
sendMessage(socket, {
id: message.id,
payload: error.message || "Unknown Error",
ok: false,
});
}
});
return response;
});
return server;
}