Skip to content

Commit 2411e41

Browse files
authored
Merge pull request #717 from kevinswiber/async-js-fetch
Updating js-fetch code to have an asyncAwaitEnabled option.
2 parents 89f2f71 + a3c4fd8 commit 2411e41

File tree

3 files changed

+106
-30
lines changed

3 files changed

+106
-30
lines changed

codegens/js-fetch/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ Convert function takes three parameters
1919
* `trimRequestBody` - Trim request body fields
2020
* `followRedirect` - Boolean denoting whether to redirect a request
2121
* `requestTimeout` - Integer denoting time after which the request will bail out in milli-seconds
22+
* `asyncAwaitEnabled` : Boolean denoting whether to use async/await syntax
2223

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

codegens/js-fetch/lib/index.js

Lines changed: 45 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ function redirectMode (redirect) {
2424
* @param {boolean} trim trim body option
2525
*/
2626
function parseURLEncodedBody (body, trim) {
27-
var bodySnippet = 'var urlencoded = new URLSearchParams();\n';
27+
var bodySnippet = 'const urlencoded = new URLSearchParams();\n';
2828
_.forEach(body, function (data) {
2929
if (!data.disabled) {
3030
bodySnippet += `urlencoded.append("${sanitize(data.key, trim)}", "${sanitize(data.value, trim)}");\n`;
@@ -40,7 +40,7 @@ function parseURLEncodedBody (body, trim) {
4040
* @param {boolean} trim trim body option
4141
*/
4242
function parseFormData (body, trim) {
43-
var bodySnippet = 'var formdata = new FormData();\n';
43+
var bodySnippet = 'const formdata = new FormData();\n';
4444
_.forEach(body, function (data) {
4545
if (!data.disabled) {
4646
if (data.type === 'file') {
@@ -65,7 +65,7 @@ function parseFormData (body, trim) {
6565
* @param {String} indentString Indentation string
6666
*/
6767
function parseRawBody (body, trim, contentType, indentString) {
68-
var bodySnippet = 'var raw = ';
68+
var bodySnippet = 'const raw = ';
6969
// Match any application type whose underlying structure is json
7070
// For example application/vnd.api+json
7171
// All of them have +json as suffix
@@ -101,7 +101,7 @@ function parseGraphQL (body, trim, indentString) {
101101
catch (e) {
102102
graphqlVariables = {};
103103
}
104-
bodySnippet = 'var graphql = JSON.stringify({\n';
104+
bodySnippet = 'const graphql = JSON.stringify({\n';
105105
bodySnippet += `${indentString}query: "${sanitize(query, trim)}",\n`;
106106
bodySnippet += `${indentString}variables: ${JSON.stringify(graphqlVariables)}\n})`;
107107
return bodySnippet;
@@ -113,7 +113,7 @@ function parseGraphQL (body, trim, indentString) {
113113
* parses binamry file data
114114
*/
115115
function parseFileData () {
116-
var bodySnippet = 'var file = "<file contents here>";\n';
116+
var bodySnippet = 'const file = "<file contents here>";\n';
117117
return bodySnippet;
118118
}
119119

@@ -154,7 +154,7 @@ function parseBody (body, trim, indentString, contentType) {
154154
function parseHeaders (headers) {
155155
var headerSnippet = '';
156156
if (!_.isEmpty(headers)) {
157-
headerSnippet = 'var myHeaders = new Headers();\n';
157+
headerSnippet = 'const myHeaders = new Headers();\n';
158158
headers = _.reject(headers, 'disabled');
159159
_.forEach(headers, function (header) {
160160
headerSnippet += `myHeaders.append("${sanitize(header.key, true)}", "${sanitize(header.value)}");\n`;
@@ -209,6 +209,13 @@ function getOptions () {
209209
type: 'boolean',
210210
default: false,
211211
description: 'Remove white space and additional lines that may affect the server\'s response'
212+
},
213+
{
214+
name: 'Use async/await',
215+
id: 'asyncAwaitEnabled',
216+
type: 'boolean',
217+
default: false,
218+
description: 'Modifies code snippet to use async/await'
212219
}
213220
];
214221
}
@@ -238,7 +245,6 @@ function convert (request, options, callback) {
238245
headerSnippet = '',
239246
bodySnippet = '',
240247
optionsSnippet = '',
241-
timeoutSnippet = '',
242248
fetchSnippet = '';
243249
indent = indent.repeat(options.indentCount);
244250
if (request.body && request.body.mode === 'graphql' && !request.headers.has('Content-Type')) {
@@ -294,8 +300,12 @@ function convert (request, options, callback) {
294300
body = request.body && request.body.toJSON();
295301
bodySnippet = parseBody(body, trim, indent, request.headers.get('Content-Type'));
296302

297-
optionsSnippet = `var requestOptions = {\n${indent}`;
298-
optionsSnippet += `method: '${request.method}',\n${indent}`;
303+
if (options.requestTimeout > 0) {
304+
codeSnippet += 'const controller = new AbortController();\n';
305+
codeSnippet += `const timerId = setTimeout(() => controller.abort(), ${options.requestTimeout});\n`;
306+
}
307+
optionsSnippet = `const requestOptions = {\n${indent}`;
308+
optionsSnippet += `method: "${request.method}",\n${indent}`;
299309
if (headerSnippet !== '') {
300310
optionsSnippet += `headers: myHeaders,\n${indent}`;
301311
codeSnippet += headerSnippet + '\n';
@@ -305,30 +315,39 @@ function convert (request, options, callback) {
305315
optionsSnippet += `body: ${body.mode},\n${indent}`;
306316
codeSnippet += bodySnippet + '\n';
307317
}
308-
optionsSnippet += `redirect: '${redirectMode(options.followRedirect)}'\n};\n`;
318+
if (options.requestTimeout > 0) {
319+
optionsSnippet += `signal: controller.signal,\n${indent}`;
320+
}
321+
optionsSnippet += `redirect: "${redirectMode(options.followRedirect)}"\n};\n`;
309322

310323
codeSnippet += optionsSnippet + '\n';
311324

312-
fetchSnippet = `fetch("${sanitize(request.url.toString())}", requestOptions)\n${indent}`;
313-
fetchSnippet += `.then(response => response.text())\n${indent}`;
314-
fetchSnippet += `.then(result => console.log(result))\n${indent}`;
315-
fetchSnippet += '.catch(error => console.log(\'error\', error));';
316-
317-
if (options.requestTimeout > 0) {
318-
timeoutSnippet = `var promise = Promise.race([\n${indent}`;
319-
timeoutSnippet += `fetch('${request.url.toString()}', requestOptions)\n${indent}${indent}`;
320-
timeoutSnippet += `.then(response => response.text()),\n${indent}`;
321-
timeoutSnippet += `new Promise((resolve, reject) =>\n${indent}${indent}`;
322-
timeoutSnippet += `setTimeout(() => reject(new Error('Timeout')), ${options.requestTimeout})\n${indent}`;
323-
timeoutSnippet += ')\n]);\n\n';
324-
timeoutSnippet += 'promise.then(result => console.log(result)),\n';
325-
timeoutSnippet += 'promise.catch(error => console.log(error));';
326-
codeSnippet += timeoutSnippet;
325+
if (options.asyncAwaitEnabled) {
326+
fetchSnippet += `try {\n${indent}`;
327+
fetchSnippet += `const response = await fetch("${sanitize(request.url.toString())}", requestOptions);\n${indent}`;
328+
fetchSnippet += `const result = await response.text();\n${indent}`;
329+
fetchSnippet += 'console.log(result)\n';
330+
fetchSnippet += `} catch (error) {\n${indent}`;
331+
fetchSnippet += 'console.error(error);\n';
332+
if (options.requestTimeout > 0) {
333+
fetchSnippet += `} finally {\n${indent}`;
334+
fetchSnippet += 'clearTimeout(timerId);\n';
335+
}
336+
fetchSnippet += '};';
327337
}
328338
else {
329-
codeSnippet += fetchSnippet;
339+
fetchSnippet = `fetch("${sanitize(request.url.toString())}", requestOptions)\n${indent}`;
340+
fetchSnippet += `.then((response) => response.text())\n${indent}`;
341+
fetchSnippet += `.then((result) => console.log(result))\n${indent}`;
342+
fetchSnippet += '.catch((error) => console.error(error))';
343+
if (options.requestTimeout > 0) {
344+
fetchSnippet += `\n${indent}.finally(() => clearTimeout(timerId))`;
345+
}
346+
fetchSnippet += ';';
330347
}
331348

349+
codeSnippet += fetchSnippet;
350+
332351
callback(null, codeSnippet);
333352
}
334353

codegens/js-fetch/test/unit/convert.test.js

Lines changed: 60 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,10 @@ describe('js-fetch convert function for test collection', function () {
2323
expect.fail(null, null, error);
2424
return;
2525
}
26-
2726
expect(snippet).to.be.a('string');
2827
snippetArray = snippet.split('\n');
2928
for (var i = 0; i < snippetArray.length; i++) {
30-
if (snippetArray[i] === 'var requestOptions = {') { line_no = i + 1; }
29+
if (snippetArray[i] === 'const requestOptions = {') { line_no = i + 1; }
3130
}
3231
expect(snippetArray[line_no].charAt(0)).to.equal(' ');
3332
expect(snippetArray[line_no].charAt(1)).to.equal(' ');
@@ -95,7 +94,7 @@ describe('js-fetch convert function for test collection', function () {
9594
return;
9695
}
9796
expect(snippet).to.be.a('string');
98-
expect(snippet).to.include('redirect: \'manual\'');
97+
expect(snippet).to.include('redirect: "manual"');
9998
});
10099
});
101100

@@ -111,7 +110,7 @@ describe('js-fetch convert function for test collection', function () {
111110
return;
112111
}
113112
expect(snippet).to.be.a('string');
114-
expect(snippet).to.include('redirect: \'follow\'');
113+
expect(snippet).to.include('redirect: "follow"');
115114
});
116115
});
117116

@@ -298,6 +297,62 @@ describe('js-fetch convert function for test collection', function () {
298297
expect(snippet).to.include('fetch("https://postman-echo.com/get?query1=b\'b&query2=c\\"c"');
299298
});
300299
});
300+
301+
it('should return snippet with promise based code when async_await is disabled', function () {
302+
const request = new sdk.Request(mainCollection.item[0].request);
303+
304+
convert(request, {}, function (error, snippet) {
305+
if (error) {
306+
expect.fail(null, null, error);
307+
}
308+
expect(snippet).to.be.a('string');
309+
expect(snippet).to.include('fetch(');
310+
expect(snippet).to.include('.then((response) => ');
311+
expect(snippet).to.include('.catch((error) => ');
312+
});
313+
});
314+
315+
it('should return snippet with async/await based code when option is enabled', function () {
316+
const request = new sdk.Request(mainCollection.item[0].request);
317+
318+
convert(request, { asyncAwaitEnabled: true }, function (error, snippet) {
319+
if (error) {
320+
expect.fail(null, null, error);
321+
}
322+
expect(snippet).to.be.a('string');
323+
expect(snippet).to.include('const response = await fetch(');
324+
expect(snippet).to.include('const result = await response.text()');
325+
expect(snippet).to.include('catch (error) {');
326+
});
327+
});
328+
329+
it('should return timeout snippet with promise based code when async_await is disabled', function () {
330+
const request = new sdk.Request(mainCollection.item[0].request);
331+
332+
convert(request, { requestTimeout: 3000 }, function (error, snippet) {
333+
if (error) {
334+
expect.fail(null, null, error);
335+
}
336+
expect(snippet).to.be.a('string');
337+
expect(snippet).to.include('const controller');
338+
expect(snippet).to.include('const timerId');
339+
expect(snippet).to.include('.finally(() => clearTimeout(timerId))');
340+
});
341+
});
342+
343+
it('should return timeout snippet with promise based code when async_await is enabled', function () {
344+
const request = new sdk.Request(mainCollection.item[0].request);
345+
346+
convert(request, { requestTimeout: 3000, asyncAwaitEnabled: true }, function (error, snippet) {
347+
if (error) {
348+
expect.fail(null, null, error);
349+
}
350+
expect(snippet).to.be.a('string');
351+
expect(snippet).to.include('const controller');
352+
expect(snippet).to.include('const timerId');
353+
expect(snippet).to.include('} finally {');
354+
});
355+
});
301356
});
302357

303358
describe('getOptions function', function () {
@@ -312,6 +367,7 @@ describe('js-fetch convert function for test collection', function () {
312367
expect(getOptions()[2]).to.have.property('id', 'requestTimeout');
313368
expect(getOptions()[3]).to.have.property('id', 'followRedirect');
314369
expect(getOptions()[4]).to.have.property('id', 'trimRequestBody');
370+
expect(getOptions()[5]).to.have.property('id', 'asyncAwaitEnabled');
315371
});
316372
});
317373

0 commit comments

Comments
 (0)