Files
UDN/index.ts
T

68 lines
1.4 KiB
TypeScript
Raw Normal View History

2024-07-05 12:48:42 +02:00
import { ServerWebSocket, write } from "bun";
import {
addConnection,
audit,
connectionCount,
forgetConnection,
processMessage,
subscriptions,
} from "./websocket-handler";
2024-07-04 17:27:46 +02:00
2024-07-05 12:48:42 +02:00
import Colors from "colors";
2024-07-04 16:11:02 +02:00
import Path from "path";
2024-07-05 12:48:42 +02:00
import { writeStat } from "./utility";
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: {
2024-07-05 12:48:42 +02:00
open() {
addConnection();
},
2024-07-04 16:18:40 +02:00
message(ws, message) {
2024-07-04 17:27:46 +02:00
processMessage(ws, message.toString());
},
2024-07-05 12:48:42 +02:00
close(ws) {
2024-07-04 18:18:44 +02:00
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));
}
2024-07-05 12:48:42 +02:00
// CLI
function output() {
console.clear();
console.log("Server up on", Colors.bold.green(server.url.toString()));
console.log();
console.log(new Date().toLocaleString());
console.log();
audit().forEach((entry) => writeStat(...entry));
}
output();
setInterval(output, 5000);