From 2ec9fa3fa9995a2e82af1ccb2f131c685ca49fe4 Mon Sep 17 00:00:00 2001 From: cha0s Date: Tue, 15 Dec 2020 02:20:13 -0600 Subject: [PATCH] refactor: serving --- packages/http/src/latus.js | 31 +++++++++---------------------- packages/http/src/server.js | 1 + 2 files changed, 10 insertions(+), 22 deletions(-) diff --git a/packages/http/src/latus.js b/packages/http/src/latus.js index 276e844..db6f003 100644 --- a/packages/http/src/latus.js +++ b/packages/http/src/latus.js @@ -41,7 +41,7 @@ const common = async (latus, req) => { return instance.webpack(); }; -const varyBy = (req) => (req.user || 0) && req.user.id; +const varyBy = () => 0; const vary = (latus, fn) => { // eslint-disable-next-line no-param-reassign @@ -86,38 +86,25 @@ const production = (latus) => vary( }; config.output.path = `${config.context}/build/assets`; const compiler = webpack(config); - let hasRun = false; - return (req, res, next) => { - if (hasRun) { - next(); - return; - } + const promise = new Promise((resolve, reject) => { compiler.run((error, stats) => { if (error) { - next(error); + reject(error); return; } - res.setHeader('Content-Type', 'application/javascript; charset=UTF-8'); if (stats.hasErrors()) { - const renderedStats = stats.toString({ + reject(new Error(stats.toString({ all: false, errors: true, - }).replace(new RegExp(process.cwd(), 'g'), '<cwd>'); - // eslint-disable-next-line no-console - console.error(renderedStats); - res.send([ - 'window.addEventListener("load", () => {', - "window.document.body.innerHTML = '
' + ",
-            `decodeURIComponent("${encodeURIComponent(renderedStats)}")`,
-            " + '
';", - '});', - ].join('')); + }).replace(new RegExp(process.cwd(), 'g'), '<cwd>'))); } else { - hasRun = true; - next(); + resolve(); } }); + }); + return (req, res, next) => { + promise.then(next).catch(next); }; }, ); diff --git a/packages/http/src/server.js b/packages/http/src/server.js index b22bff5..e8ef338 100644 --- a/packages/http/src/server.js +++ b/packages/http/src/server.js @@ -74,6 +74,7 @@ export const createHttpServer = async (latus) => { else { app.use(express.static(join(__dirname, 'client'))); app.get('*', async (req, res) => { + res.setHeader('Content-Type', 'text/html; charset=UTF-8'); const stream = createReadStream(join(__dirname, 'client', 'index.html')); stream.pipe(res); });