diff --git a/modInfo.json b/modInfo.json index 4579193..e084a3f 100644 --- a/modInfo.json +++ b/modInfo.json @@ -1,4 +1,4 @@ { "name": "SVR.JS Cache mod", - "version": "1.0.1" + "version": "1.0.2" } diff --git a/src/index.js b/src/index.js index 55b920c..8838c73 100644 --- a/src/index.js +++ b/src/index.js @@ -69,11 +69,13 @@ module.exports = function (req, res, logFacilities, config, next) { // Capture the response const originalWriteHead = res.writeHead.bind(res); + const originalWrite = res.write.bind(res); const originalEnd = res.end.bind(res); let writtenHeaders = res.getHeaders(); let writtenStatusCode = 200; let responseBody = ""; let maximumCachedResponseSizeExceeded = false; + let piping = false; res.writeHead = function (statusCode, statusCodeDescription, headers) { const properHeaders = headers ? headers : statusCodeDescription; @@ -174,7 +176,34 @@ module.exports = function (req, res, logFacilities, config, next) { }; if (req.method != "HEAD") { + res.write = function (chunk, encoding, callback) { + if (!piping && chunk && !maximumCachedResponseSizeExceeded) { + const processedChunk = Buffer.from( + chunk, + typeof encoding === "string" ? encoding : undefined + ).toString("latin1"); + if ( + maximumCachedResponseSize !== null && + maximumCachedResponseSize !== undefined && + responseBody.length + processedChunk.length > + maximumCachedResponseSize + ) { + maximumCachedResponseSizeExceeded = true; + } else { + try { + responseBody += processedChunk; + // eslint-disable-next-line no-unused-vars + } catch (err) { + maximumCachedResponseSizeExceeded = true; + } + } + } + + originalWrite(chunk, encoding, callback); + }; + res.on("pipe", (src) => { + piping = true; src.on("data", (chunk) => { if (!maximumCachedResponseSizeExceeded) { const processedChunk = Buffer.from(chunk).toString("latin1"); @@ -196,6 +225,10 @@ module.exports = function (req, res, logFacilities, config, next) { } }); }); + + res.on("unpipe", () => { + piping = false; + }); } next(); // Continue with normal processing diff --git a/tests/index.test.js b/tests/index.test.js index 6b335e9..30561aa 100644 --- a/tests/index.test.js +++ b/tests/index.test.js @@ -30,6 +30,7 @@ describe("SVR.JS Cache mod", () => { res = { headers: {}, writeHead: resWriteHead, + write: jest.fn(), end: resEnd, setHeader: jest.fn(), getHeaderNames: jest.fn(() => []),