Skip to content

Commit

Permalink
Merge pull request #717 from kevinswiber/async-js-fetch
Browse files Browse the repository at this point in the history
Updating js-fetch code to have an asyncAwaitEnabled option.
  • Loading branch information
VShingala committed Jul 20, 2023
2 parents 89f2f71 + a3c4fd8 commit 2411e41
Show file tree
Hide file tree
Showing 3 changed files with 106 additions and 30 deletions.
1 change: 1 addition & 0 deletions codegens/js-fetch/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ Convert function takes three parameters
* `trimRequestBody` - Trim request body fields
* `followRedirect` - Boolean denoting whether to redirect a request
* `requestTimeout` - Integer denoting time after which the request will bail out in milli-seconds
* `asyncAwaitEnabled` : Boolean denoting whether to use async/await syntax

* `callback` - callback function with first parameter as error and second parameter as string for code snippet

Expand Down
71 changes: 45 additions & 26 deletions codegens/js-fetch/lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ function redirectMode (redirect) {
* @param {boolean} trim trim body option
*/
function parseURLEncodedBody (body, trim) {
var bodySnippet = 'var urlencoded = new URLSearchParams();\n';
var bodySnippet = 'const urlencoded = new URLSearchParams();\n';
_.forEach(body, function (data) {
if (!data.disabled) {
bodySnippet += `urlencoded.append("${sanitize(data.key, trim)}", "${sanitize(data.value, trim)}");\n`;
Expand All @@ -40,7 +40,7 @@ function parseURLEncodedBody (body, trim) {
* @param {boolean} trim trim body option
*/
function parseFormData (body, trim) {
var bodySnippet = 'var formdata = new FormData();\n';
var bodySnippet = 'const formdata = new FormData();\n';
_.forEach(body, function (data) {
if (!data.disabled) {
if (data.type === 'file') {
Expand All @@ -65,7 +65,7 @@ function parseFormData (body, trim) {
* @param {String} indentString Indentation string
*/
function parseRawBody (body, trim, contentType, indentString) {
var bodySnippet = 'var raw = ';
var bodySnippet = 'const raw = ';
// Match any application type whose underlying structure is json
// For example application/vnd.api+json
// All of them have +json as suffix
Expand Down Expand Up @@ -101,7 +101,7 @@ function parseGraphQL (body, trim, indentString) {
catch (e) {
graphqlVariables = {};
}
bodySnippet = 'var graphql = JSON.stringify({\n';
bodySnippet = 'const graphql = JSON.stringify({\n';
bodySnippet += `${indentString}query: "${sanitize(query, trim)}",\n`;
bodySnippet += `${indentString}variables: ${JSON.stringify(graphqlVariables)}\n})`;
return bodySnippet;
Expand All @@ -113,7 +113,7 @@ function parseGraphQL (body, trim, indentString) {
* parses binamry file data
*/
function parseFileData () {
var bodySnippet = 'var file = "<file contents here>";\n';
var bodySnippet = 'const file = "<file contents here>";\n';
return bodySnippet;
}

Expand Down Expand Up @@ -154,7 +154,7 @@ function parseBody (body, trim, indentString, contentType) {
function parseHeaders (headers) {
var headerSnippet = '';
if (!_.isEmpty(headers)) {
headerSnippet = 'var myHeaders = new Headers();\n';
headerSnippet = 'const myHeaders = new Headers();\n';
headers = _.reject(headers, 'disabled');
_.forEach(headers, function (header) {
headerSnippet += `myHeaders.append("${sanitize(header.key, true)}", "${sanitize(header.value)}");\n`;
Expand Down Expand Up @@ -209,6 +209,13 @@ function getOptions () {
type: 'boolean',
default: false,
description: 'Remove white space and additional lines that may affect the server\'s response'
},
{
name: 'Use async/await',
id: 'asyncAwaitEnabled',
type: 'boolean',
default: false,
description: 'Modifies code snippet to use async/await'
}
];
}
Expand Down Expand Up @@ -238,7 +245,6 @@ function convert (request, options, callback) {
headerSnippet = '',
bodySnippet = '',
optionsSnippet = '',
timeoutSnippet = '',
fetchSnippet = '';
indent = indent.repeat(options.indentCount);
if (request.body && request.body.mode === 'graphql' && !request.headers.has('Content-Type')) {
Expand Down Expand Up @@ -294,8 +300,12 @@ function convert (request, options, callback) {
body = request.body && request.body.toJSON();
bodySnippet = parseBody(body, trim, indent, request.headers.get('Content-Type'));

optionsSnippet = `var requestOptions = {\n${indent}`;
optionsSnippet += `method: '${request.method}',\n${indent}`;
if (options.requestTimeout > 0) {
codeSnippet += 'const controller = new AbortController();\n';
codeSnippet += `const timerId = setTimeout(() => controller.abort(), ${options.requestTimeout});\n`;
}
optionsSnippet = `const requestOptions = {\n${indent}`;
optionsSnippet += `method: "${request.method}",\n${indent}`;
if (headerSnippet !== '') {
optionsSnippet += `headers: myHeaders,\n${indent}`;
codeSnippet += headerSnippet + '\n';
Expand All @@ -305,30 +315,39 @@ function convert (request, options, callback) {
optionsSnippet += `body: ${body.mode},\n${indent}`;
codeSnippet += bodySnippet + '\n';
}
optionsSnippet += `redirect: '${redirectMode(options.followRedirect)}'\n};\n`;
if (options.requestTimeout > 0) {
optionsSnippet += `signal: controller.signal,\n${indent}`;
}
optionsSnippet += `redirect: "${redirectMode(options.followRedirect)}"\n};\n`;

codeSnippet += optionsSnippet + '\n';

fetchSnippet = `fetch("${sanitize(request.url.toString())}", requestOptions)\n${indent}`;
fetchSnippet += `.then(response => response.text())\n${indent}`;
fetchSnippet += `.then(result => console.log(result))\n${indent}`;
fetchSnippet += '.catch(error => console.log(\'error\', error));';

if (options.requestTimeout > 0) {
timeoutSnippet = `var promise = Promise.race([\n${indent}`;
timeoutSnippet += `fetch('${request.url.toString()}', requestOptions)\n${indent}${indent}`;
timeoutSnippet += `.then(response => response.text()),\n${indent}`;
timeoutSnippet += `new Promise((resolve, reject) =>\n${indent}${indent}`;
timeoutSnippet += `setTimeout(() => reject(new Error('Timeout')), ${options.requestTimeout})\n${indent}`;
timeoutSnippet += ')\n]);\n\n';
timeoutSnippet += 'promise.then(result => console.log(result)),\n';
timeoutSnippet += 'promise.catch(error => console.log(error));';
codeSnippet += timeoutSnippet;
if (options.asyncAwaitEnabled) {
fetchSnippet += `try {\n${indent}`;
fetchSnippet += `const response = await fetch("${sanitize(request.url.toString())}", requestOptions);\n${indent}`;
fetchSnippet += `const result = await response.text();\n${indent}`;
fetchSnippet += 'console.log(result)\n';
fetchSnippet += `} catch (error) {\n${indent}`;
fetchSnippet += 'console.error(error);\n';
if (options.requestTimeout > 0) {
fetchSnippet += `} finally {\n${indent}`;
fetchSnippet += 'clearTimeout(timerId);\n';
}
fetchSnippet += '};';
}
else {
codeSnippet += fetchSnippet;
fetchSnippet = `fetch("${sanitize(request.url.toString())}", requestOptions)\n${indent}`;
fetchSnippet += `.then((response) => response.text())\n${indent}`;
fetchSnippet += `.then((result) => console.log(result))\n${indent}`;
fetchSnippet += '.catch((error) => console.error(error))';
if (options.requestTimeout > 0) {
fetchSnippet += `\n${indent}.finally(() => clearTimeout(timerId))`;
}
fetchSnippet += ';';
}

codeSnippet += fetchSnippet;

callback(null, codeSnippet);
}

Expand Down
64 changes: 60 additions & 4 deletions codegens/js-fetch/test/unit/convert.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,10 @@ describe('js-fetch convert function for test collection', function () {
expect.fail(null, null, error);
return;
}

expect(snippet).to.be.a('string');
snippetArray = snippet.split('\n');
for (var i = 0; i < snippetArray.length; i++) {
if (snippetArray[i] === 'var requestOptions = {') { line_no = i + 1; }
if (snippetArray[i] === 'const requestOptions = {') { line_no = i + 1; }
}
expect(snippetArray[line_no].charAt(0)).to.equal(' ');
expect(snippetArray[line_no].charAt(1)).to.equal(' ');
Expand Down Expand Up @@ -95,7 +94,7 @@ describe('js-fetch convert function for test collection', function () {
return;
}
expect(snippet).to.be.a('string');
expect(snippet).to.include('redirect: \'manual\'');
expect(snippet).to.include('redirect: "manual"');
});
});

Expand All @@ -111,7 +110,7 @@ describe('js-fetch convert function for test collection', function () {
return;
}
expect(snippet).to.be.a('string');
expect(snippet).to.include('redirect: \'follow\'');
expect(snippet).to.include('redirect: "follow"');
});
});

Expand Down Expand Up @@ -298,6 +297,62 @@ describe('js-fetch convert function for test collection', function () {
expect(snippet).to.include('fetch("https://postman-echo.com/get?query1=b\'b&query2=c\\"c"');
});
});

it('should return snippet with promise based code when async_await is disabled', function () {
const request = new sdk.Request(mainCollection.item[0].request);

convert(request, {}, function (error, snippet) {
if (error) {
expect.fail(null, null, error);
}
expect(snippet).to.be.a('string');
expect(snippet).to.include('fetch(');
expect(snippet).to.include('.then((response) => ');
expect(snippet).to.include('.catch((error) => ');
});
});

it('should return snippet with async/await based code when option is enabled', function () {
const request = new sdk.Request(mainCollection.item[0].request);

convert(request, { asyncAwaitEnabled: true }, function (error, snippet) {
if (error) {
expect.fail(null, null, error);
}
expect(snippet).to.be.a('string');
expect(snippet).to.include('const response = await fetch(');
expect(snippet).to.include('const result = await response.text()');
expect(snippet).to.include('catch (error) {');
});
});

it('should return timeout snippet with promise based code when async_await is disabled', function () {
const request = new sdk.Request(mainCollection.item[0].request);

convert(request, { requestTimeout: 3000 }, function (error, snippet) {
if (error) {
expect.fail(null, null, error);
}
expect(snippet).to.be.a('string');
expect(snippet).to.include('const controller');
expect(snippet).to.include('const timerId');
expect(snippet).to.include('.finally(() => clearTimeout(timerId))');
});
});

it('should return timeout snippet with promise based code when async_await is enabled', function () {
const request = new sdk.Request(mainCollection.item[0].request);

convert(request, { requestTimeout: 3000, asyncAwaitEnabled: true }, function (error, snippet) {
if (error) {
expect.fail(null, null, error);
}
expect(snippet).to.be.a('string');
expect(snippet).to.include('const controller');
expect(snippet).to.include('const timerId');
expect(snippet).to.include('} finally {');
});
});
});

describe('getOptions function', function () {
Expand All @@ -312,6 +367,7 @@ describe('js-fetch convert function for test collection', function () {
expect(getOptions()[2]).to.have.property('id', 'requestTimeout');
expect(getOptions()[3]).to.have.property('id', 'followRedirect');
expect(getOptions()[4]).to.have.property('id', 'trimRequestBody');
expect(getOptions()[5]).to.have.property('id', 'asyncAwaitEnabled');
});
});

Expand Down

0 comments on commit 2411e41

Please sign in to comment.