Skip to content

Commit

Permalink
Merge pull request #725 from magieno/2024-09-add-response-time-to-htt…
Browse files Browse the repository at this point in the history
…p-client

- Calculates the response time
  • Loading branch information
etiennenoel authored Sep 15, 2024
2 parents a4e1efb + 32a9937 commit 0a193b3
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
10 changes: 10 additions & 0 deletions packages/http/src/interfaces/http-response.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,14 @@ export interface HttpResponseInterface {
* The request that was sent for getting this response.
*/
request: HttpRequestInterface;

/**
* The time it took to get the response (in ms).
*/
responseTime?: number;

/**
* The time it took to get the first byte of the response (in ms).
*/
timeToFirstByte?: number;
}
7 changes: 7 additions & 0 deletions packages/http/src/wrappers/http.wrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ export class HttpWrapper implements HttpWrapperInterface {
executeRequest(request: HttpRequestInterface): Promise<HttpResponseInterface> {
return new Promise((resolve, reject) => {
// Define the options required by the http and https modules.
let now: number = -1;

const url = new URL(request.url);
const options: RequestOptions = {
host: url.hostname,
Expand All @@ -48,20 +50,25 @@ export class HttpWrapper implements HttpWrapperInterface {
let body = '';

res.on('data', chunk => {
response.timeToFirstByte = performance.now() - now;
body = body + "" + chunk;
});

res.on('error', error => {
response.responseTime = performance.now() - now;
return reject(error);
})

res.on('end', async () => {
response.body = body;
response.responseTime = performance.now() - now;

return resolve(response);
});
}

now = performance.now();

// Make the http or https call depending on the url.
if (url.protocol === "http://" || url.protocol === "http:" || url.protocol === "http") {
const req = httpRequest(options, callback);
Expand Down

0 comments on commit 0a193b3

Please sign in to comment.