egg
Version:
A web application framework for Node.js
37 lines (36 loc) • 1.25 kB
JavaScript
import { fileURLToPath } from "node:url";
import path from "node:path";
import { readFile } from "node:fs/promises";
//#region src/app/middleware/site_file.ts
const BUFFER_CACHE = Symbol("siteFile URL buffer cache");
var site_file_default = (options) => {
return async function siteFile(ctx, next) {
if (ctx.method !== "HEAD" && ctx.method !== "GET") return next();
if (ctx.path[0] !== "/") return next();
let content = options[ctx.path];
if (!content) return next();
if (typeof content === "function") content = await content(ctx);
if (typeof content === "string") return ctx.redirect(content);
if (content instanceof URL) {
if (content.protocol !== "file:") return ctx.redirect(content.href);
let buffer = Reflect.get(content, BUFFER_CACHE);
if (!buffer) {
buffer = await readFile(fileURLToPath(content));
Reflect.set(content, BUFFER_CACHE, buffer);
}
ctx.set("cache-control", options.cacheControl);
ctx.body = content;
ctx.type = path.extname(ctx.path);
return;
}
if (Buffer.isBuffer(content)) {
ctx.set("cache-control", options.cacheControl);
ctx.body = content;
ctx.type = path.extname(ctx.path);
return;
}
return next();
};
};
//#endregion
export { site_file_default as default };