chore: release SVR.JS Cache mod 1.0.2

This commit is contained in:
Dorian Niemiec 2024-12-20 16:33:20 +01:00
parent 5b4f2a0983
commit b236e84f09
3 changed files with 35 additions and 1 deletions

View file

@ -1,4 +1,4 @@
{ {
"name": "SVR.JS Cache mod", "name": "SVR.JS Cache mod",
"version": "1.0.1" "version": "1.0.2"
} }

View file

@ -69,11 +69,13 @@ module.exports = function (req, res, logFacilities, config, next) {
// Capture the response // Capture the response
const originalWriteHead = res.writeHead.bind(res); const originalWriteHead = res.writeHead.bind(res);
const originalWrite = res.write.bind(res);
const originalEnd = res.end.bind(res); const originalEnd = res.end.bind(res);
let writtenHeaders = res.getHeaders(); let writtenHeaders = res.getHeaders();
let writtenStatusCode = 200; let writtenStatusCode = 200;
let responseBody = ""; let responseBody = "";
let maximumCachedResponseSizeExceeded = false; let maximumCachedResponseSizeExceeded = false;
let piping = false;
res.writeHead = function (statusCode, statusCodeDescription, headers) { res.writeHead = function (statusCode, statusCodeDescription, headers) {
const properHeaders = headers ? headers : statusCodeDescription; const properHeaders = headers ? headers : statusCodeDescription;
@ -174,7 +176,34 @@ module.exports = function (req, res, logFacilities, config, next) {
}; };
if (req.method != "HEAD") { 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) => { res.on("pipe", (src) => {
piping = true;
src.on("data", (chunk) => { src.on("data", (chunk) => {
if (!maximumCachedResponseSizeExceeded) { if (!maximumCachedResponseSizeExceeded) {
const processedChunk = Buffer.from(chunk).toString("latin1"); 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 next(); // Continue with normal processing

View file

@ -30,6 +30,7 @@ describe("SVR.JS Cache mod", () => {
res = { res = {
headers: {}, headers: {},
writeHead: resWriteHead, writeHead: resWriteHead,
write: jest.fn(),
end: resEnd, end: resEnd,
setHeader: jest.fn(), setHeader: jest.fn(),
getHeaderNames: jest.fn(() => []), getHeaderNames: jest.fn(() => []),