@belmonddev/catch-request-express-middleware 3.3.3 → 3.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/index.js +23 -18
  2. package/package.json +1 -1
package/index.js CHANGED
@@ -17,6 +17,24 @@ const override = (module, attr, fn) => {
17
17
  export const getHeaderValue = (headers, key) =>
18
18
  Object.entries(headers || {}).find(([k]) => k.toLowerCase() === key)?.[1];
19
19
 
20
+ function tryDecompress(buffer) {
21
+ if (zlib.brotliDecompressSync) {
22
+ try {
23
+ return zlib.brotliDecompressSync(buffer);
24
+ } catch {
25
+ try {
26
+ return zlib.gunzipSync(buffer);
27
+ } catch {
28
+ try {
29
+ return zlib.inflateSync(buffer);
30
+ } catch {
31
+ return buffer;
32
+ }
33
+ }
34
+ }
35
+ }
36
+ }
37
+
20
38
  const catchHttpResponse = (reqObject, responseCb) => {
21
39
  override(reqObject, 'emit', (result, eventName, response) => {
22
40
  const chunks = [];
@@ -32,24 +50,10 @@ const catchHttpResponse = (reqObject, responseCb) => {
32
50
  statusCode: response.statusCode,
33
51
  statusMessage: response.statusMessage,
34
52
  };
35
- const contentEncoding = getHeaderValue(
36
- response.headers,
37
- 'content-encoding'
38
- );
39
- if (['gzip', 'deflate'].indexOf(contentEncoding) !== -1) {
40
- const buffer = Buffer.concat(chunks);
41
- const zlibFunc =
42
- contentEncoding === 'gzip' ? zlib.gunzip : zlib.inflate;
43
- zlibFunc(buffer, (_, decoded) => {
44
- const stringBody = decoded.toString('utf8');
45
- const request = { ...responseObj, body: stringBody };
46
- responseCb(request);
47
- });
48
- } else {
49
- const stringBody = chunks.map((c) => c.toString('utf8')).join('');
50
- const request = { ...responseObj, body: stringBody };
51
- responseCb(request);
52
- }
53
+ const buffer = Buffer.concat(chunks);
54
+ const stringBody = tryDecompress(buffer).toString('utf8');
55
+ const request = { ...responseObj, body: stringBody };
56
+ responseCb(request);
53
57
  });
54
58
  }
55
59
  }
@@ -165,6 +169,7 @@ const catchExpressIncomingRequest = (req, res, incomingRequestCb) => {
165
169
  // we override write method ASAP cause otherwise if the request finishes too fast the response callback is not called
166
170
  let writeCount = 0;
167
171
  let firstData = '';
172
+ res.bodyWritten = '';
168
173
  override(req.socket, 'write', (result, data) => {
169
174
  writeCount++;
170
175
  if (writeCount === 1) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@belmonddev/catch-request-express-middleware",
3
- "version": "3.3.3",
3
+ "version": "3.3.5",
4
4
  "main": "index.js",
5
5
  "author": "David Escalera",
6
6
  "license": "ISC",