Skip to content

Commit

Permalink
fix: add basic support for insomnia.request.size()
Browse files Browse the repository at this point in the history
  • Loading branch information
ihexxa committed Jan 8, 2025
1 parent f311ac2 commit bb947a4
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 4 deletions.
38 changes: 37 additions & 1 deletion packages/insomnia-sdk/src/objects/__tests__/request.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';

import { mergeRequestBody, Request, RequestBody, toScriptRequestBody } from '../request';
import { Header, HeaderList } from '../headers';
import { calculateRequestSize, mergeRequestBody, Request, RequestBody, RequestBodyOptions, toScriptRequestBody } from '../request';

describe('test request and response objects', () => {
it('test RequestBody methods', () => {
Expand Down Expand Up @@ -115,4 +116,39 @@ describe('test request and response objects', () => {
expect(mergeRequestBody(scriptReqBody, originalReqBody)).toEqual(originalReqBody);
});
});

const reqBodyTestCases: { body: RequestBodyOptions; headers: HeaderList<Header>; expectedTotal: number }[] = [
{
body: {
mode: 'raw',
raw: '1',
},
headers: new HeaderList<Header>(undefined, []),
expectedTotal: 1,
},
{
body: {
mode: 'raw',
raw: '😎',
},
headers: new HeaderList<Header>(undefined, []),
expectedTotal: 4,
},
{
body: {
mode: 'raw',
raw: '睡',
},
headers: new HeaderList<Header>(undefined, []),
expectedTotal: 3,
},
];

reqBodyTestCases.forEach(({ body, headers, expectedTotal }) => {
it(`test calculateRequestSize: ${body.raw}`, () => {
const reqSize = calculateRequestSize(new RequestBody(body), headers);

expect(reqSize.total).toEqual(expectedTotal);
});
});
});
28 changes: 25 additions & 3 deletions packages/insomnia-sdk/src/objects/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,10 @@ export class RequestBody extends PropertyBase {
}

override toString() {
if (this.mode === undefined) {
return '';
}

try {
switch (this.mode) {
case 'formdata':
Expand Down Expand Up @@ -375,9 +379,9 @@ export class Request extends Property {
this.url.removeQueryParams(params);
}

// TODO:
// size(): RequestSize {
// }
size(): RequestSize {
return calculateRequestSize(this.body, this.headers);
}

override toJSON() {
return {
Expand Down Expand Up @@ -657,3 +661,21 @@ export function mergeRequests(
...updatedReqProperties,
};
}

export function calculateRequestSize(body: RequestBody | undefined, headers: HeaderList<Header>): RequestSize {
const bodySize = new Blob([(body || '').toString()]).size;
const headerSize = new Blob([
headers.reduce(
(acc, header) => (acc + header.toString() + '\n'),
'',
{},
),
]).size;

return {
body: bodySize,
header: headerSize,
total: bodySize + headerSize,
source: 'COMPUTED',
};
}

0 comments on commit bb947a4

Please sign in to comment.