Skip to content

Commit

Permalink
feat: add getSize method to BrunoResponse and update related shims an…
Browse files Browse the repository at this point in the history
…d translations
  • Loading branch information
sanish-bruno committed Feb 12, 2025
1 parent 31c1183 commit 705b8b5
Show file tree
Hide file tree
Showing 10 changed files with 189 additions and 127 deletions.
13 changes: 1 addition & 12 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion packages/bruno-app/src/components/CodeEditor/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ if (!SERVER_RENDERED) {
'res.getHeaders()',
'res.getBody()',
'res.getResponseTime()',
'res.getSize()',
'req',
'req.url',
'req.method',
Expand Down Expand Up @@ -83,7 +84,7 @@ if (!SERVER_RENDERED) {
'bru.runner',
'bru.runner.setNextRequest(requestName)',
'bru.runner.skipRequest()',
'bru.runner.stopExecution()',
'bru.runner.stopExecution()'
];
CodeMirror.registerHelper('hint', 'brunoJS', (editor, options) => {
const cursor = editor.getCursor();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ const replacements = {
'pm\\.expect\\.fail\\(': 'expect.fail(',
'pm\\.response\\.responseTime': 'res.getResponseTime()',
'pm\\.environment\\.name': 'bru.getEnvName()',
'pm\\.response\\.status': 'res.statusText()',
'pm\\.response\\.headers': 'res.headers',
'pm\\.response\\.size': 'res.getSize()',
"tests\\['([^']+)'\\]\\s*=\\s*([^;]+);": 'test("$1", function() { expect(Boolean($2)).to.be.true; });',
// deprecated translations
'postman\\.setEnvironmentVariable\\(': 'bru.setEnvVar(',
Expand All @@ -27,7 +30,7 @@ const replacements = {
'pm\\.execution\\.skipRequest\\(\\)': 'bru.runner.skipRequest()',
'pm\\.execution\\.skipRequest': 'bru.runner.skipRequest',
'pm\\.execution\\.setNextRequest\\(null\\)': 'bru.runner.stopExecution()',
'pm\\.execution\\.setNextRequest\\(\'null\'\\)': 'bru.runner.stopExecution()',
"pm\\.execution\\.setNextRequest\\('null'\\)": 'bru.runner.stopExecution()'
};

const extendedReplacements = Object.keys(replacements).reduce((acc, key) => {
Expand Down
38 changes: 17 additions & 21 deletions packages/bruno-cli/src/runner/run-single-request.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ const { createFormData } = require('../utils/form-data');
const protocolRegex = /^([-+\w]{1,25})(:?\/\/|:)/;
const { NtlmClient } = require('axios-ntlm');


const onConsoleLog = (type, args) => {
console[type](...args);
};
Expand All @@ -50,7 +49,7 @@ const runSingleRequest = async function (
let item = {
pathname: path.join(collectionPath, filename),
...bruJson
}
};
request = prepareRequest(item, collection);

request.__bruno__executionMode = 'cli';
Expand Down Expand Up @@ -265,29 +264,28 @@ const runSingleRequest = async function (
if (!options.disableCookies) {
const cookieString = getCookieStringForUrl(request.url);
if (cookieString && typeof cookieString === 'string' && cookieString.length) {
const existingCookieHeaderName = Object.keys(request.headers).find(
name => name.toLowerCase() === 'cookie'
);
const existingCookieHeaderName = Object.keys(request.headers).find((name) => name.toLowerCase() === 'cookie');
const existingCookieString = existingCookieHeaderName ? request.headers[existingCookieHeaderName] : '';

// Helper function to parse cookies into an object
const parseCookies = (str) => str.split(';').reduce((cookies, cookie) => {
const parseCookies = (str) =>
str.split(';').reduce((cookies, cookie) => {
const [name, ...rest] = cookie.split('=');
if (name && name.trim()) {
cookies[name.trim()] = rest.join('=').trim();
cookies[name.trim()] = rest.join('=').trim();
}
return cookies;
}, {});
}, {});

const mergedCookies = {
...parseCookies(existingCookieString),
...parseCookies(cookieString),
...parseCookies(existingCookieString),
...parseCookies(cookieString)
};

const combinedCookieString = Object.entries(mergedCookies)
.map(([name, value]) => `${name}=${value}`)
.join('; ');
.map(([name, value]) => `${name}=${value}`)
.join('; ');

request.headers[existingCookieHeaderName || 'Cookie'] = combinedCookieString;
}
}
Expand All @@ -307,13 +305,11 @@ const runSingleRequest = async function (

let response, responseTime;
try {

let axiosInstance = makeAxiosInstance();
if (request.ntlmConfig) {
axiosInstance=NtlmClient(request.ntlmConfig,axiosInstance.defaults)
axiosInstance = NtlmClient(request.ntlmConfig, axiosInstance.defaults);
delete request.ntlmConfig;
}


if (request.awsv4config) {
// todo: make this happen in prepare-request.js
Expand Down Expand Up @@ -375,7 +371,7 @@ const runSingleRequest = async function (
data: null,
responseTime: 0
},
error: err?.message || err?.errors?.map(e => e?.message)?.at(0) || err?.code || 'Request Failed!',
error: err?.message || err?.errors?.map((e) => e?.message)?.at(0) || err?.code || 'Request Failed!',
assertionResults: [],
testResults: [],
nextRequestName: nextRequestName,
Expand All @@ -388,7 +384,7 @@ const runSingleRequest = async function (

console.log(
chalk.green(stripExtension(filename)) +
chalk.dim(` (${response.status} ${response.statusText}) - ${responseTime} ms`)
chalk.dim(` (${response.status} ${response.statusText}) - ${responseTime} ms`)
);

// run post-response vars
Expand Down
15 changes: 14 additions & 1 deletion packages/bruno-cli/src/utils/axios-instance.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ function makeAxiosInstance() {
const instance = axios.create({
proxy: false,
headers: {
"User-Agent": `bruno-runtime/${CLI_VERSION}`
'User-Agent': `bruno-runtime/${CLI_VERSION}`
}
});

Expand All @@ -26,13 +26,26 @@ function makeAxiosInstance() {
const end = Date.now();
const start = response.config.headers['request-start-time'];
response.headers['request-duration'] = end - start;
// response size is the sum of the response data and the headers, should it include anything else?
const responseSize =
Buffer.byteLength(response.data) +
Object.keys(response.headers).reduce((total, key) => total + Buffer.byteLength(key + response.headers[key]), 0);
response.headers['response-size'] = responseSize;
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;
// response size is the sum of the response data and the headers, should it include anything else?
const responseSize =
Buffer.byteLength(error.response.data) +
Object.keys(error.response.headers).reduce(
(total, key) => total + Buffer.byteLength(key + error.response.headers[key]),
0
);
error.response.headers['response-size'] = responseSize;
}
return Promise.reject(error);
}
Expand Down
19 changes: 16 additions & 3 deletions packages/bruno-electron/src/ipc/network/axios-instance.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ const URL = require('url');
const Socket = require('net').Socket;
const axios = require('axios');
const connectionCache = new Map(); // Cache to store checkConnection() results
const electronApp = require("electron");
const electronApp = require('electron');

const LOCAL_IPV6 = '::1';
const LOCAL_IPV4 = '127.0.0.1';
const LOCALHOST = 'localhost';
const version = electronApp?.app?.getVersion()?.substring(1) ?? "";
const version = electronApp?.app?.getVersion()?.substring(1) ?? '';

const getTld = (hostname) => {
if (!hostname) {
Expand Down Expand Up @@ -69,7 +69,7 @@ function makeAxiosInstance() {
},
proxy: false,
headers: {
"User-Agent": `bruno-runtime/${version}`
'User-Agent': `bruno-runtime/${version}`
}
});

Expand Down Expand Up @@ -99,13 +99,26 @@ function makeAxiosInstance() {
const end = Date.now();
const start = response.config.headers['request-start-time'];
response.headers['request-duration'] = end - start;
// response size is the sum of the response data and the headers, should it include anything else?
const responseSize =
Buffer.byteLength(response.data) +
Object.keys(response.headers).reduce((total, key) => total + Buffer.byteLength(key + response.headers[key]), 0);
response.headers['response-size'] = responseSize;
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;
// response size is the sum of the response data and the headers, should it include anything else?
const responseSize =
Buffer.byteLength(error.response.data) +
Object.keys(error.response.headers).reduce(
(total, key) => total + Buffer.byteLength(key + error.response.headers[key]),
0
);
error.response.headers['response-size'] = responseSize;
}
return Promise.reject(error);
}
Expand Down
Loading

0 comments on commit 705b8b5

Please sign in to comment.