-
Notifications
You must be signed in to change notification settings - Fork 1
/
durable-objects.ts
55 lines (44 loc) · 1.06 KB
/
durable-objects.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
interface Env {
EchoDo: DurableObjectNamespace;
}
/**
* no-op fetch handler as we only use the durable object from this service.
*/
export default {
async fetch(_request: Request, _env: Env, _ctx: ExecutionContext) {
return new Response(null, { status: 200 });
},
};
let textDecoder = new TextDecoder("utf-8");
export class EchoDo {
#state: DurableObjectState;
constructor(state: DurableObjectState, _env: Env) {
this.#state = state;
}
async fetch(request: Request) {
let url = new URL(request.url);
switch (url.pathname) {
case "/join": {
let client = this.#join();
return new Response(null, { status: 101, webSocket: client });
}
case "/broadcast": {
break;
}
default: {
return new Response(null, { status: 404 });
}
}
}
#join() {
let { 0: client, 1: server } = new WebSocketPair();
this.#state.acceptWebSocket(server);
return client;
}
webSocketMessage(ws: WebSocket, message: string | ArrayBuffer) {
if (message instanceof ArrayBuffer) {
message = textDecoder.decode(message);
}
ws.send(message);
}
}