(resp, transformHtml)
| 12 | |
| 13 | // Inspired by `resp-modifier` https://github.com/shakyShane/resp-modifier/blob/4a000203c9db630bcfc3b6bb8ea2abc090ae0139/index.js |
| 14 | function wrapResponse(resp, transformHtml) { |
| 15 | resp._wrappedOriginalWrite = resp.write; |
| 16 | resp._wrappedOriginalWriteHead = resp.writeHead; |
| 17 | resp._wrappedOriginalEnd = resp.end; |
| 18 | |
| 19 | resp._wrappedHeaders = []; |
| 20 | resp._wrappedTransformHtml = transformHtml; |
| 21 | resp._hasEnded = false; |
| 22 | resp._shouldForceEnd = false; |
| 23 | |
| 24 | // Compatibility with web standards Response() |
| 25 | Object.defineProperty(resp, "body", { |
| 26 | // Returns write cache |
| 27 | get: function() { |
| 28 | if(typeof this._writeCache === "string") { |
| 29 | return this._writeCache; |
| 30 | } |
| 31 | }, |
| 32 | // Usage: |
| 33 | // res.body = ""; // overwrite existing content |
| 34 | // res.body += ""; // append to existing content, can also res.write("") to append |
| 35 | set: function(data) { |
| 36 | if(typeof data === "string") { |
| 37 | this._writeCache = data; |
| 38 | } |
| 39 | } |
| 40 | }); |
| 41 | |
| 42 | // Compatibility with web standards Response() |
| 43 | Object.defineProperty(resp, "bodyUsed", { |
| 44 | get: function() { |
| 45 | return this._hasEnded; |
| 46 | } |
| 47 | }) |
| 48 | |
| 49 | // Original signature writeHead(statusCode[, statusMessage][, headers]) |
| 50 | resp.writeHead = function(statusCode, ...args) { |
| 51 | let headers = args[args.length - 1]; |
| 52 | // statusMessage is a string |
| 53 | if(typeof headers !== "string") { |
| 54 | this._contentType = getContentType(headers); |
| 55 | } |
| 56 | |
| 57 | if((this._contentType || "").startsWith("text/html")) { |
| 58 | this._wrappedHeaders.push([statusCode, ...args]); |
| 59 | } else { |
| 60 | return this._wrappedOriginalWriteHead(statusCode, ...args); |
| 61 | } |
| 62 | return this; |
| 63 | } |
| 64 | |
| 65 | // data can be a String or Buffer |
| 66 | resp.write = function(data, ...args) { |
| 67 | if(typeof data === "string") { |
| 68 | if(!this._writeCache) { |
| 69 | this._writeCache = ""; |
| 70 | } |
| 71 |
no test coverage detected
searching dependent graphs…