refactor: serving

This commit is contained in:
cha0s 2020-12-15 02:20:13 -06:00
parent a4c02dac7a
commit 2ec9fa3fa9
2 changed files with 10 additions and 22 deletions

View File

@ -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 = '<pre>' + ",
`decodeURIComponent("${encodeURIComponent(renderedStats)}")`,
" + '</pre>';",
'});',
].join(''));
}).replace(new RegExp(process.cwd(), 'g'), '&lt;cwd&gt;')));
}
else {
hasRun = true;
next();
resolve();
}
});
});
return (req, res, next) => {
promise.then(next).catch(next);
};
},
);

View File

@ -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);
});