Created
October 30, 2024 01:26
-
-
Save aabccd021/1ab1f7862cdf0db7691fba749d884f2a to your computer and use it in GitHub Desktop.
Bun mime middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import mimes from "mime"; | |
type RequestHandler = (req: Request) => Promise<Response>; | |
export function middleware(fetch: RequestHandler): RequestHandler { | |
return async (req) => { | |
if (req.method !== "GET") { | |
return fetch(req); | |
} | |
const response = await fetch(req); | |
if (response.status !== 200) { | |
return response; | |
} | |
const contentTypeAlereadySet = | |
response.headers.get("Content-Type") !== null; | |
if (contentTypeAlereadySet) { | |
return response; | |
} | |
const path = new URL(req.url).pathname; | |
const extension = path.split(".").at(-1); | |
if (extension === undefined) { | |
return response; | |
} | |
const mimeType = mimes.getType(extension); | |
if (mimeType === null) { | |
return response; | |
} | |
response.headers.set("Content-Type", mimeType); | |
return response; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment