Skip to content

Commit

Permalink
Fix cache
Browse files Browse the repository at this point in the history
  • Loading branch information
mhluska committed Aug 29, 2018
1 parent a5d194e commit e498159
Showing 1 changed file with 25 additions and 8 deletions.
33 changes: 25 additions & 8 deletions src/express-http-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,23 +87,40 @@ class ExpressHTTPServer {
}

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);
};
}
}
Expand Down

0 comments on commit e498159

Please sign in to comment.