import {Request, Response, NextFunction} from "express"; import * as mm from "micromatch"; 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(htmlTpl: string, mainModule: {default: (path: string) => Promise<{ssrInitStoreKey: string; data: any; html: string}>}, proxyMap: {[key: string]: any} | Array<{context: string[] | string}> | Function = {}) { const passUrls = getProxys(proxyMap); const arr = htmlTpl.match(/\s*`); 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 || "服务器错误!"); } } }; if (htmlChunks[1]) { res.write(htmlChunks[0]); } try { mainModule .default(req.url) .then(result => { const {ssrInitStoreKey, data, html} = result; if (res.headersSent) { res.write(htmlChunks[1].replace(/[^>]*[^<]*/m, `${html}`).replace(//, ``)); res.end(); } else { res.send(htmlChunks[0].replace(/[^>]*[^<]*/m, `${html}`).replace(//, ``)); } }) .catch(errorHandler); } catch (err) { errorHandler(err); } } }; }