Files
UDN/index.ts
T

45 lines
1006 B
TypeScript
Raw Normal View History

2024-07-04 17:27:46 +02:00
import { forgetConnection, processMessage } from "./websocket-handler";
2024-07-04 16:11:02 +02:00
import Path from "path";
2024-07-04 17:27:46 +02:00
import { ServerWebSocket } from "bun";
2024-07-04 16:11:02 +02:00
// CONFIG
const staticDir = "static/dist";
const defaultPage = "index.html";
2024-07-04 17:27:46 +02:00
// TYPES
export type WS = ServerWebSocket<unknown>;
2024-07-04 16:11:02 +02:00
// SERVER
const server = Bun.serve({
fetch(request, server) {
2024-07-04 16:18:40 +02:00
// allow websockets
server.upgrade(request);
2024-07-04 16:11:02 +02:00
2024-07-04 16:18:40 +02:00
// respond
const requestPath = new URL(request.url).pathname;
2024-07-04 18:02:53 +02:00
switch (requestPath) {
case "/":
return createFileResponse(defaultPage);
default:
return createFileResponse(requestPath);
2024-07-04 16:11:02 +02:00
}
},
2024-07-04 16:18:40 +02:00
websocket: {
message(ws, message) {
2024-07-04 17:27:46 +02:00
processMessage(ws, message.toString());
},
close(ws, code, reason) {
forgetConnection(ws);
2024-07-04 16:18:40 +02:00
},
},
2024-07-04 16:11:02 +02:00
});
function createFileResponse(requestPath: string): Response {
const fullPath = Path.join(staticDir, requestPath);
return new Response(Bun.file(fullPath));
}
console.log(`Server up on port ${server.port}.`);