Skip to content

Commit

Permalink
fix: variables in request body import are replaced
Browse files Browse the repository at this point in the history
  • Loading branch information
AnWeber committed Jan 9, 2023
1 parent cb4e927 commit 80ef2de
Show file tree
Hide file tree
Showing 9 changed files with 62 additions and 34 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
## 5.10.1 (2023-01-09)

#### Fix

- variables in request body import are replaced (#377)

## 5.10.0 (2023-01-08)

#### Features
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

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

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"license": "MIT",
"publisher": "AnWeber",
"description": "HTTP/REST CLI Client for *.http files",
"version": "5.10.0",
"version": "5.10.1",
"homepage": "https://github.com/AnWeber/httpyac",
"repository": {
"type": "git",
Expand Down
19 changes: 18 additions & 1 deletion src/httpYacApi.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,23 @@ query company_query {
'{"query":"query company_query {\\n company {\\n coo\\n }\\n}","operationName":"company_query"}'
);
});
it('imported buffer body with replace', async () => {
const body = JSON.stringify({ foo: 'foo', bar: '{{bar}}' }, null, 2);
initFileProvider({ 'body.json': body });
const mockedEndpoints = await localServer.forPost('/post').thenReply(200);

await exec(`
@bar=bar2
POST http://localhost:8080/post
Content-Type: application/json
<@ ./body.json
`);

const requests = await mockedEndpoints.getSeenRequests();
expect(requests[0].headers['content-type']).toBe('application/json');
expect(await requests[0].body.getText()).toBe(JSON.stringify({ foo: 'foo', bar: 'bar2' }, null, 2));
});
});

describe('metadata', () => {
Expand Down Expand Up @@ -717,7 +734,7 @@ Authorization: Basic john doe
const missingAuthEndpoints = await localServer
.forGet('/json')
.matching(request => !request.headers.authorization)
.thenReply(401, null, {
.thenReply(401, undefined, {
'www-authenticate':
'Digest realm="json@localhost",qop="auth,auth-int",nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",opaque="5ccc069c403ebaf9f0171e9517f40e41"',
});
Expand Down
9 changes: 5 additions & 4 deletions src/plugins/core/parseEnd/closeRequestBody.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,12 +85,13 @@ async function toHttpRequestBodyLineArray(rawBody: Array<string | models.Request
if (utils.isString(line)) {
result.push(line);
} else {
const forceInjectVariables = (filename: string, context: models.ProcessorContext) => {
const { injectVariables, fileName } = line;
const forceInjectVariables = (file: string, context: models.ProcessorContext) => {
if (context.httpRegion.metaData.injectVariables) {
return true;
}
if (context.config?.requestBodyInjectVariablesExtensions) {
const extname = utils.extensionName(filename);
const extname = utils.extensionName(file);
if (extname) {
return context.config.requestBodyInjectVariablesExtensions.indexOf(extname) >= 0;
}
Expand All @@ -99,8 +100,8 @@ async function toHttpRequestBodyLineArray(rawBody: Array<string | models.Request
};
result.push(
async (context: models.ProcessorContext) =>
await utils.replaceFilePath(line.fileName, context, async (path: models.PathLike) => {
if (forceInjectVariables(line.fileName, context) || line.injectVariables) {
await utils.replaceFilePath(fileName, context, async (path: models.PathLike) => {
if (injectVariables || forceInjectVariables(line.fileName, context)) {
return await fileProvider.readFile(path, line.encoding);
}
return fileProvider.readBuffer(path);
Expand Down
13 changes: 13 additions & 0 deletions src/plugins/core/request/encodeRequestBody.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import * as models from '../../../models';
import * as utils from '../../../utils';
import encodeUrl from 'encodeurl';

export async function encodeRequestBody(request: models.Request): Promise<void> {
if (request.body) {
if (utils.isString(request.body)) {
if (utils.isMimeTypeFormUrlEncoded(request.contentType)) {
request.body = encodeUrl(request.body);
}
}
}
}
4 changes: 3 additions & 1 deletion src/plugins/core/request/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as models from '../../../models';
import { attachDefaultHeaders } from './attachDefaultHeaders';
import { encodeRequestBody } from './encodeRequestBody';
import { isTrustedInterceptor } from './isTrustedInterceptor';
import { requestVariableReplacer } from './requestVariableReplacer';
import { setEnvRequestOptions } from './setEnvRequestOptions';
Expand All @@ -8,8 +9,9 @@ import { transformRequestBodyToBuffer } from './transformRequestBodyToBuffer';
export function initOnRequestHook(api: models.HttpyacHooksApi) {
api.hooks.onRequest.addHook('attachDefaultHeaders', attachDefaultHeaders);
api.hooks.onRequest.addHook('setEnvRequestOptions', setEnvRequestOptions);
api.hooks.onRequest.addHook('requestVariableReplacer', requestVariableReplacer);
api.hooks.onRequest.addHook('transformRequestBody', transformRequestBodyToBuffer);
api.hooks.onRequest.addHook('requestVariableReplacer', requestVariableReplacer);
api.hooks.onRequest.addHook('encodeRequestBody', encodeRequestBody);

api.hooks.onRequest.addInterceptor(isTrustedInterceptor);
}
12 changes: 5 additions & 7 deletions src/plugins/core/request/transformRequestBodyToBuffer.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ import { transformRequestBodyToBuffer } from './transformRequestBodyToBuffer';
describe('transformRequestBodyToBuffer', () => {
it('should return same string', async () => {
const request: models.Request = { body: 'foo' };
await transformRequestBodyToBuffer(request);
await transformRequestBodyToBuffer(request, {} as models.ProcessorContext);
expect(request.body).toEqual('foo');
});
it('should return merged buffer', async () => {
const request: models.Request = {
body: [() => Promise.resolve(Buffer.from('foo')), 'bar'],
};
await transformRequestBodyToBuffer(request);
await transformRequestBodyToBuffer(request, {} as models.ProcessorContext);
expect(Buffer.isBuffer(request.body)).toBeTruthy();
if (Buffer.isBuffer(request.body)) {
expect(request.body.toString('utf-8')).toBe('foobar');
Expand All @@ -21,10 +21,8 @@ describe('transformRequestBodyToBuffer', () => {
const request: models.Request = {
body: ['foo', 'bar'],
};
await transformRequestBodyToBuffer(request);
expect(Buffer.isBuffer(request.body)).toBeTruthy();
if (Buffer.isBuffer(request.body)) {
expect(request.body.toString('utf-8')).toBe('foobar');
}
await transformRequestBodyToBuffer(request, {} as models.ProcessorContext);
expect(typeof request.body === 'string').toBeTruthy();
expect(request.body).toBe('foobar');
});
});
27 changes: 9 additions & 18 deletions src/plugins/core/request/transformRequestBodyToBuffer.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,12 @@
import * as models from '../../../models';
import * as utils from '../../../utils';
import encodeUrl from 'encodeurl';

export async function transformRequestBodyToBuffer(
request: models.Request,
context: models.ProcessorContext
): Promise<void> {
if (request.body) {
if (utils.isString(request.body)) {
if (utils.isMimeTypeFormUrlEncoded(request.contentType)) {
request.body = encodeUrl(request.body);
}
} else if (
Array.isArray(request.body) &&
request.body.every(obj => ['function', 'string'].indexOf(typeof obj) >= 0)
) {
if (Array.isArray(request.body) && request.body.every(obj => ['function', 'string'].indexOf(typeof obj) >= 0)) {
request.body = await normalizeBody(request.body, context);
}
}
Expand All @@ -23,21 +15,20 @@ export async function transformRequestBodyToBuffer(
async function normalizeBody(
body: Array<models.HttpRequestBodyLine>,
context: models.ProcessorContext
): Promise<Buffer> {
const buffers: Array<Buffer> = [];
): Promise<Buffer | string> {
const buffers: Array<Buffer | string> = [];
for (const obj of body) {
if (utils.isString(obj)) {
buffers.push(Buffer.from(obj));
buffers.push(obj);
} else {
const result = await obj(context);
if (result) {
if (utils.isString(result)) {
buffers.push(Buffer.from(result));
} else {
buffers.push(result);
}
buffers.push(result);
}
}
}
return Buffer.concat(buffers);
if (buffers.some(obj => Buffer.isBuffer(obj))) {
return Buffer.concat(buffers.map(obj => (Buffer.isBuffer(obj) ? obj : Buffer.from(obj))));
}
return buffers.join('');
}

0 comments on commit 80ef2de

Please sign in to comment.