@esmx/core
Version:
A high-performance microfrontend framework supporting Vue, React, Preact, Solid, and Svelte with SSR and Module Federation capabilities.
53 lines (52 loc) • 1.41 kB
JavaScript
import send from "send";
const reFinal = /\.final\.[a-zA-Z0-9]+$/;
export function isImmutableFile(filename) {
return reFinal.test(filename);
}
export function createMiddleware(esmx) {
const middlewares = Object.values(esmx.moduleConfig.links).map(
(item) => {
const base = `/${item.name}/`;
const baseUrl = new URL(`file:`);
const root = item.client;
return (req, res, next) => {
const url = req.url ?? "/";
const { pathname } = new URL(req.url ?? "/", baseUrl);
if (!url.startsWith(base) || req.method !== "GET") {
next();
return;
}
send(req, pathname.substring(base.length - 1), {
root
}).on("headers", () => {
if (isImmutableFile(pathname)) {
res.setHeader(
"cache-control",
"public, max-age=31536000, immutable"
);
} else {
res.setHeader("cache-control", "no-cache");
}
}).pipe(res);
};
}
);
return mergeMiddlewares(middlewares);
}
export function mergeMiddlewares(middlewares) {
return (req, res, next) => {
let index = 0;
function dispatch() {
if (index < middlewares.length) {
middlewares[index](req, res, () => {
index++;
dispatch();
});
return;
} else {
next();
}
}
dispatch();
};
}