Skip to content

Commit

Permalink
docs: add more code comments
Browse files Browse the repository at this point in the history
  • Loading branch information
gr2m committed Dec 21, 2021
1 parent 7c0d6b2 commit a50fc17
Showing 1 changed file with 9 additions and 0 deletions.
9 changes: 9 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,15 @@ export default {
return;
}

// hook into `http.Server.prototype.onSocket` in order to get
// access to the `http.ClientRequest` instance of every request
// sent using the `http(s)` modules.
origOnSocket = http.ClientRequest.prototype.onSocket;
http.ClientRequest.prototype.onSocket = function (socket) {
const interceptedRequest = this;

// read the request body as an array of Buffer chuncks
// by hooking into the `request.write` method.
const requestBodyChunks = [];
const originalRequestWrite = interceptedRequest.write;
interceptedRequest.write = function (chunk) {
Expand All @@ -25,11 +30,13 @@ export default {
};

interceptedRequest.on("response", async (response) => {
// read the response body as an array of Buffer chuncks
const responseBodyChunks = [];
for await (const chunk of response) {
responseBodyChunks.push(Buffer.from(chunk));
}

// emit the `request` event with the request and response body
emitter.emit("record", {
request: interceptedRequest,
requestBody: requestBodyChunks,
Expand All @@ -38,6 +45,8 @@ export default {
});
});

// run the original `http.Server.prototype.onSocket` method
// and return its value
return origOnSocket.call(this, socket);
};

Expand Down

0 comments on commit a50fc17

Please sign in to comment.