Fixes 944 | Remove the check for returning more than one JSON result in Response Plugin (#5192)

* Remove the check for returning more than one result in JSON. If it's an array of objects, the following lines will just stringify. This allows the response to be parsed by JSONPath

* Update test to permit more than one result

* add edge-case

Co-authored-by: Filipe Freire <livrofubia@gmail.com>
This commit is contained in:
Brian GoadandFilipe Freire authored and GitHub committed 2022-10-25 09:25:39 +00:00
1 parent d102de2850
commit 7dd07ba2fe
2 files changed
+30 -11

No files matched your search

@@ -150,7 +150,7 @@ describe('Response tag', () => {
}
});
it('fails on more than 1 result', async () => {
it('allows more than 1 result if array of strings', async () => {
const requests = [{ _id: 'req_1', parentId: 'wrk_1' }];
const responses = [
@@ -165,12 +165,29 @@ describe('Response tag', () => {
const context = _genTestContext(requests, responses);
try {
await tag.run(context, 'body', 'req_1', '$.array.*');
fail('JSON should have failed to parse');
} catch (err) {
expect(err.message).toContain('Returned more than one result: $.array.*');
}
const result = await tag.run(context, 'body', 'req_1', '$.array');
expect(result).toBe('["bar","baz"]');
});
it('allows more than 1 result if array of integers', async () => {
const requests = [{ _id: 'req_1', parentId: 'wrk_1' }];
const responses = [
{
_id: 'res_1',
parentId: 'req_1',
statusCode: 200,
contentType: 'application/json',
_body: '{"array": [1, 2]}',
},
];
const context = _genTestContext(requests, responses);
const result = await tag.run(context, 'body', 'req_1', '$.array');
expect(result).toBe('[1,2]');
});
it('works with utf-16 encoding', async () => {
+6 -4
View File
@@ -134,7 +134,7 @@ module.exports.templateTags = [
shouldResend = ageSeconds > maxAgeSeconds;
}
break;
case 'always':
shouldResend = true;
break;
@@ -209,7 +209,7 @@ module.exports.templateTags = [
console.warn('[response] Failed to decode body', err);
body = bodyBuffer.toString();
}
if (sanitizedFilter.indexOf('$') === 0) {
return matchJSONPath(body, sanitizedFilter);
} else {
@@ -241,8 +241,10 @@ function matchJSONPath(bodyStr, query) {
if (results.length === 0) {
throw new Error(`Returned no results: ${query}`);
} else if (results.length > 1) {
throw new Error(`Returned more than one result: ${query}`);
}
if (results.length > 1 ) {
return JSON.stringify(results);
}
if (typeof results[0] !== 'string') {