import axios from "axios"; import {Request, Response, NextFunction} from "express"; import * as mm from "micromatch"; const Module: {new (): any} = module.constructor as any; function getProxys(proxyMap: {[key: string]: any} | Array<{context: string[] | string}> | Function) { if (typeof proxyMap === "function") { proxyMap = proxyMap(); } if (Array.isArray(proxyMap)) { proxyMap = proxyMap.reduce((pre, cur) => { const url = cur.context; if (typeof url === "string") { pre[url] = true; } else { for (const key of url) { pre[key] = true; } } return pre; }, {}); } return Object.keys(proxyMap); } export default function middleware(enable: boolean, proxyMap: {[key: string]: any} | Array<{context: string[] | string}> | Function = {}) { if (!enable) { return function(req: Request, res: Response, next: NextFunction) { next(); }; } const passUrls = [...getProxys(proxyMap), "/index.html", "/server/**", "/client/**", "/sockjs-node/**", "**/*.hot-update.*"]; return (req: Request, res: Response, next: NextFunction) => { if (passUrls.some(reg => mm.isMatch(req.url, reg))) { next(); } else { const errorHandler = (err: any) => { if (err.code === "301" || err.code === "302") { if (res.headersSent) { res.write(`跳转中。。。`); res.end(); } else { res.redirect(parseInt(err.code, 10), err.detail); } } else { console.error(err); if (res.headersSent) { res.write(`

${err.message || "服务器错误!"}

`); res.end(); } else { res.send(err.message || "服务器错误!"); } } }; try { Promise.all([axios.get(`${req.protocol}://${req.headers.host}/server/main.js`), axios.get(`${req.protocol}://${req.headers.host}/index.html`)]) .then(([main, tpl]) => { const arr = tpl.data.match(/\s*`)); res.end(); } else { res.send(htmlChunks[0].replace(/[^>]*[^<]*/m, `${html}`).replace(//, ``)); } }); }) .catch(errorHandler); } catch (err) { errorHandler(err); } } }; }