Refactor MIME type helper function and move outside server block

This commit is contained in:
2025-09-10 03:05:55 +02:00
parent 6863d91438
commit e5b01203b8

View File

@@ -1,15 +1,8 @@
// server.ts // server.ts
const server = Bun.serve({ // Helper function to get MIME type
port: 5173, function getMimeType(filename: string): string {
async fetch(req) { switch (filename.split(".").pop()?.toLowerCase()) {
const url = new URL(req.url);
const pathname = url.pathname;
// Helper function to get MIME type
function getMimeType(filename: string): string {
const ext = filename.split(".").pop()?.toLowerCase();
switch (ext) {
case "js": case "js":
return "application/javascript"; return "application/javascript";
case "ts": case "ts":
@@ -32,7 +25,13 @@ const server = Bun.serve({
default: default:
return "text/plain"; return "text/plain";
} }
} }
const server = Bun.serve({
port: 5173,
async fetch(req) {
const url = new URL(req.url);
const pathname = url.pathname;
// Serve root as index.html // Serve root as index.html
if (pathname === "/") if (pathname === "/")
@@ -56,11 +55,9 @@ const server = Bun.serve({
if (!exists) if (!exists)
return new Response(`File not found: ${filename}`, { status: 404 }); return new Response(`File not found: ${filename}`, { status: 404 });
const mimeType = getMimeType(filename);
return new Response(file, { return new Response(file, {
headers: { headers: {
"Content-Type": mimeType, "Content-Type": getMimeType(filename),
}, },
}); });
} catch (error) { } catch (error) {