diff --git a/src/express-http-server.js b/src/express-http-server.js index 2aef6cf9..0992036a 100644 --- a/src/express-http-server.js +++ b/src/express-http-server.js @@ -30,8 +30,22 @@ class ExpressHTTPServer { this.beforeMiddleware(app); + if (this.cache) { + app.get('/*', this.buildCacheMiddleware()); + } + if (this.gzip) { - this.app.use(require('compression')()); + app.use(require('compression')()); + } + + if (this.cache) { + app.use(function(req, res, next) { + if (res.body) { + res.send(res.body); + } else { + next(); + } + }); } if (username !== undefined || password !== undefined) { @@ -39,10 +53,6 @@ class ExpressHTTPServer { app.use(basicAuth(username, password)); } - if (this.cache) { - app.get('/*', this.buildCacheMiddleware()); - } - if (this.distPath) { app.get('/', fastbootMiddleware); app.use(express.static(this.distPath)); @@ -75,35 +85,52 @@ class ExpressHTTPServer { .then(response => { if (response) { this.ui.writeLine(`cache hit; path=${path}`); - res.send(response); + res.body = response; } else { this.ui.writeLine(`cache miss; path=${path}`); this.interceptResponseCompletion(path, res); - next(); } + next(); }) .catch(() => next()); }; } interceptResponseCompletion(path, res) { - let send = res.send.bind(res); + let prevWrite = res.write; + let prevEnd = res.end; + let chunks = []; + let cache = this.cache; + let ui = this.ui; + + let pushChunk = (chunk) => { + if (!chunk) return; + chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); + }; + + res.write = function(chunk) { + pushChunk(chunk); + prevWrite.apply(res, arguments); + }; + + res.end = function(chunk) { + pushChunk(chunk); - res.send = (body) => { - let ret = send(body); + let body = Buffer.concat(chunks).toString(); - this.cache.put(path, body, res) + cache.put(path, body, res) .then(() => { - this.ui.writeLine(`stored in cache; path=${path}`); + ui.writeLine(`stored in cache; path=${path}`); }) .catch(() => { let truncatedBody = body.replace(/\n/g).substr(0, 200); - this.ui.writeLine(`error storing cache; path=${path}; body=${truncatedBody}...`); + ui.writeLine(`error storing cache; path=${path}; body=${truncatedBody}...`); }); - res.send = send; + res.write = prevWrite; + res.end = prevEnd; - return ret; + prevEnd.apply(res, arguments); }; } } diff --git a/src/worker.js b/src/worker.js index 72f83151..befc2bbf 100644 --- a/src/worker.js +++ b/src/worker.js @@ -37,6 +37,7 @@ class Worker { } if (!this.httpServer.cache) { this.httpServer.cache = this.cache; } + if (!this.httpServer.gzip) { this.httpServer.gzip = this.gzip; } if (!this.httpServer.distPath) { this.httpServer.distPath = this.distPath; } if (!this.httpServer.ui) { this.httpServer.ui = this.ui; } }