Use axios interceptor to measure response time

This commit is contained in:
Stefan Ollinger 2023-10-05 17:46:12 +02:00
parent efbdde8252
commit bb7d13d2d9
2 changed files with 54 additions and 8 deletions

View File

@ -10,6 +10,7 @@ const interpolateVars = require('./interpolate-vars');
const { ScriptRuntime, TestRuntime, VarsRuntime, AssertRuntime } = require('@usebruno/js');
const { stripExtension } = require('../utils/filesystem');
const { getOptions } = require('../utils/bru');
const { makeAxiosInstance } = require('../utils/axios-instance');
const runSingleRequest = async function (
filename,
@ -123,15 +124,23 @@ const runSingleRequest = async function (
}
let response, responseTime;
const start = Date.now();
try {
// run request
response = await axios(request);
responseTime = Date.now() - start;
const axiosInstance = makeAxiosInstance();
/** @type {import('axios').AxiosResponse} */
response = await axiosInstance(request);
// Prevents the duration on leaking to the actual result
responseTime = response.headers.get('request-duration');
response.headers.delete('request-duration');
} catch (err) {
if (err && err.response) {
response = err.response;
responseTime = Date.now() - start;
// Prevents the duration on leaking to the actual result
responseTime = response.headers.get('request-duration');
response.headers.delete('request-duration');
} else {
console.log(chalk.red(stripExtension(filename)) + chalk.dim(` (${err.message})`));
return {
@ -155,10 +164,7 @@ const runSingleRequest = async function (
}
}
console.log(
chalk.green(stripExtension(filename)) +
chalk.dim(` (${response.status} ${response.statusText}) - ${responseTime} ms`)
);
console.log(chalk.green(stripExtension(filename)) + chalk.dim(` (${response.status} ${response.statusText}) - ${responseTime} ms`));
// run post-response vars
const postResponseVars = get(bruJson, 'request.vars.res');

View File

@ -0,0 +1,40 @@
const axios = require('axios');
/**
* Function that configures axios with timing interceptors
* Important to note here that the timings are not completely accurate.
* @see https://github.com/axios/axios/issues/695
* @returns {import('axios').AxiosStatic}
*/
function makeAxiosInstance() {
/** @type {import('axios').AxiosStatic} */
const instance = axios.create();
instance.interceptors.request.use((config) => {
config.headers['request-start-time'] = Date.now();
return config;
});
instance.interceptors.response.use(
(response) => {
const end = Date.now();
const start = response.config.headers['request-start-time'];
response.headers['request-duration'] = end - start;
return response;
},
(error) => {
if (error.response) {
const end = Date.now();
const start = error.config.headers['request-start-time'];
error.response.headers['request-duration'] = end - start;
}
return Promise.reject(error);
}
);
return instance;
}
module.exports = {
makeAxiosInstance
};