@belmonddev/catch-request-express-middleware 1.1.0 → 1.2.0
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.
- package/index.js +33 -18
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -97,6 +97,17 @@ const overrideHttpModule = (httpModule, requestSentCb) => {
|
|
|
97
97
|
});
|
|
98
98
|
};
|
|
99
99
|
|
|
100
|
+
const callResponseCb = (responseCb, res) => {
|
|
101
|
+
responseCb({
|
|
102
|
+
headers: res.getHeaders(),
|
|
103
|
+
statusCode: res.statusCode,
|
|
104
|
+
statusMessage: res.statusMessage,
|
|
105
|
+
body: /application\/json;?.*?$/.test(res.getHeaders()['content-type'])
|
|
106
|
+
? JSON.parse(res.bodyWritten)
|
|
107
|
+
: res.bodyWritten,
|
|
108
|
+
});
|
|
109
|
+
};
|
|
110
|
+
|
|
100
111
|
const callReceivedCbs = (req, res, requestReceivedCb) => {
|
|
101
112
|
const responseCb = requestReceivedCb({
|
|
102
113
|
headers: req.headers,
|
|
@@ -108,30 +119,34 @@ const callReceivedCbs = (req, res, requestReceivedCb) => {
|
|
|
108
119
|
body: req.body,
|
|
109
120
|
});
|
|
110
121
|
if (responseCb) {
|
|
111
|
-
let body = '';
|
|
112
|
-
let writeCount = 0;
|
|
113
|
-
override(req.socket, 'write', (result, data) => {
|
|
114
|
-
writeCount++;
|
|
115
|
-
if (writeCount === 2) {
|
|
116
|
-
body = data.toString();
|
|
117
|
-
}
|
|
118
|
-
});
|
|
119
|
-
|
|
120
122
|
req.socket.setMaxListeners(100);
|
|
121
|
-
req.
|
|
122
|
-
responseCb
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
body: /application\/json;?.*?$/.test(res.getHeaders()['content-type'])
|
|
127
|
-
? JSON.parse(body)
|
|
128
|
-
: body,
|
|
123
|
+
if (req.socketClosed) {
|
|
124
|
+
callResponseCb(responseCb, res);
|
|
125
|
+
} else {
|
|
126
|
+
req.socket.on('close', () => {
|
|
127
|
+
callResponseCb(responseCb, res);
|
|
129
128
|
});
|
|
130
|
-
}
|
|
129
|
+
}
|
|
131
130
|
}
|
|
132
131
|
};
|
|
133
132
|
|
|
134
133
|
const catchExpressReceivedRequest = (req, res, requestReceivedCb) => {
|
|
134
|
+
// we override write method ASAP cause otherwise if the request finishes too fast the response callback is not called
|
|
135
|
+
let writeCount = 0;
|
|
136
|
+
let firstData = '';
|
|
137
|
+
override(req.socket, 'write', (result, data) => {
|
|
138
|
+
writeCount++;
|
|
139
|
+
if (writeCount === 1) {
|
|
140
|
+
firstData = data;
|
|
141
|
+
} else if (writeCount === 2) {
|
|
142
|
+
res.bodyWritten = data.toString();
|
|
143
|
+
if (!res.bodyWritten.length) {
|
|
144
|
+
res.bodyWritten = firstData.split('\r\n\r\n')?.[1];
|
|
145
|
+
}
|
|
146
|
+
req.socketClosed = true;
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
|
|
135
150
|
if (req.headers['content-type'] !== 'application/json') {
|
|
136
151
|
let body = '';
|
|
137
152
|
req.on('data', function (data) {
|