-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
159 lines (127 loc) · 3.59 KB
/
index.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { v5 } from "https://deno.land/[email protected]/uuid/mod.ts";
function mime(text: string) {
const ext = text.split(".").pop();
const dict: Record<string, string> = {
"js": "text/javascript",
"json": "application/json",
"html": "text/html",
"css": "text/css",
};
return ext && ext in dict ? dict[ext] : "text/plain";
}
const textEncoder = new TextEncoder();
const createEvent = (eventName: string, data: Object) =>
textEncoder.encode(`event: ${eventName}\ndata: ${JSON.stringify(data)}\n\n`);
const openRooms: Map<string, string | null> = new Map();
async function joinRoom(roomId: string) {
if (openRooms.has(roomId)) {
const peerId = await v5.generate(
roomId,
textEncoder.encode(crypto.randomUUID()),
);
// First one to join room is host.
if (openRooms.get(roomId) === null) {
openRooms.set(roomId, peerId);
}
const channel = new BroadcastChannel(roomId);
// Connect to room;
const body = new ReadableStream<Uint8Array>({
start: (controller) => {
controller.enqueue(createEvent("id", peerId));
channel.onmessage = (e) => {
const body = createEvent(e.data.type, e.data.value);
controller.enqueue(body);
};
},
cancel() {
channel.close();
},
});
return new Response(body, {
status: 200,
headers: new Headers({
"Connection": "Keep-Alive",
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
}),
});
} else {
throw new Error("Room does not exist");
}
}
function createRoom(roomId: string) {
if (openRooms.has(roomId)) {
throw new Error("Room exists");
} else {
openRooms.set(roomId, null);
}
}
function emitInRoom(roomId: string, event: { type: string; value: any }) {
const channel = new BroadcastChannel(roomId);
channel.postMessage(event);
}
function errorResponse(e: Error) {
return new Response(e.message, {
status: 500,
});
}
async function router(request: Request) {
const url = new URL(request.url);
let response: Promise<Response> | Response = errorResponse(
new Error("Not found"),
);
if (url.pathname.includes("/room/")) {
const [, , roomId, sse] = url.pathname.split("/");
if (request.method === "OPTION") {
response = new Response("OK", {
status: 204,
});
}
if (roomId && request.method === "GET" && sse === "sse") {
response = joinRoom(roomId);
}
if (roomId && request.method === "POST" && sse === "sse") {
const event = await request.json();
emitInRoom(roomId, event);
response = new Response("OK", {
status: 200,
});
}
if (roomId === "create" && request.method === "POST") {
const roomId = crypto.randomUUID();
createRoom(roomId);
response = new Response(
JSON.stringify({
roomId,
}),
{
headers: new Headers({
"Cache-Control": "no-cache",
"Content-Type": mime(".json"),
}),
},
);
}
}
return response;
}
async function handler(request: Request): Promise<Response> {
let response: Response;
try {
response = await router(request);
response.headers.append(
"Access-Control-Allow-Origin",
"*",
);
response.headers.append(
"Access-Control-Request-Method",
"POST, GET, OPTIONS",
);
} catch (e) {
response = errorResponse(e);
}
return response;
}
console.log("App is running at http://localhost:8000/station");
await serve(handler);