Skip to content

Commit 171de96

Browse files
committed
Adds nodejs-axios codegen
- added axios support
1 parent ad51688 commit 171de96

17 files changed

+1380
-0
lines changed

codegens/nodejs-axios/.gitignore

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
.DS_Store
2+
# Logs
3+
logs
4+
*.log
5+
npm-debug.log*
6+
yarn-debug.log*
7+
yarn-error.log*
8+
9+
# Coverage directory used by tools like istanbul
10+
.coverage
11+
12+
# node-waf configuration
13+
.lock-wscript
14+
15+
16+
# Dependency directories
17+
node_modules/
18+
jspm_packages/
19+
20+
# Typescript v1 declaration files
21+
typings/
22+
23+
# Optional npm cache directory
24+
.npm
25+
26+
# Optional eslint cache
27+
.eslintcache
28+
29+
# Optional REPL history
30+
.node_repl_history
31+
32+
# Output of 'npm pack'
33+
*.tgz
34+
35+
# Yarn Integrity file
36+
.yarn-integrity
37+
38+
# dotenv environment variables file
39+
.env
40+
41+
out/

codegens/nodejs-axios/.npmignore

+76
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
### NPM Specific: Disregard recursive project files
2+
### ===============================================
3+
/.editorconfig
4+
/.gitmodules
5+
/test
6+
7+
### Borrowed from .gitignore
8+
### ========================
9+
10+
# Logs
11+
logs
12+
*.log
13+
npm-debug.log*
14+
yarn-debug.log*
15+
yarn-error.log*
16+
17+
# Runtime data
18+
pids
19+
*.pid
20+
*.seed
21+
*.pid.lock
22+
23+
# Prevent IDE stuff
24+
.idea
25+
.vscode
26+
*.sublime-*
27+
28+
# Directory for instrumented libs generated by jscoverage/JSCover
29+
lib-cov
30+
31+
# Coverage directory used by tools like istanbul
32+
.coverage
33+
34+
# nyc test coverage
35+
.nyc_output
36+
37+
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
38+
.grunt
39+
40+
# Bower dependency directory (https://bower.io/)
41+
bower_components
42+
43+
# node-waf configuration
44+
.lock-wscript
45+
46+
# Compiled binary addons (http://nodejs.org/api/addons.html)
47+
build/Release
48+
49+
# Dependency directories
50+
node_modules/
51+
jspm_packages/
52+
53+
# Typescript v1 declaration files
54+
typings/
55+
56+
# Optional npm cache directory
57+
.npm
58+
59+
# Optional eslint cache
60+
.eslintcache
61+
62+
# Optional REPL history
63+
.node_repl_history
64+
65+
# Output of 'npm pack'
66+
*.tgz
67+
68+
# Yarn Integrity file
69+
.yarn-integrity
70+
71+
# dotenv environment variables file
72+
.env
73+
74+
snippet.swift
75+
76+
out/

codegens/nodejs-axios/README.md

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
2+
> Converts Postman-SDK Request into code snippet for .
3+
4+
#### Prerequisites
5+
To run Code-Gen, ensure that you have NodeJS >= v8. A copy of the NodeJS installable can be downloaded from https://nodejs.org/en/download/package-manager.
6+
7+
## Using the Module
8+
The module will expose an object which will have property `convert` which is the function for converting the Postman-SDK request to swift code snippet.
9+
10+
### convert function
11+
Convert function takes three parameters
12+
13+
* `request` - Postman-SDK Request Object
14+
15+
* `options` - options is an object which hsa following properties
16+
* `indentType` - String denoting type of indentation for code snippet. eg: 'Space', 'Tab'
17+
* `indentCount` - The number of indentation characters to add per code level
18+
* `trimRequestBody` - Whether or not request body fields should be trimmed
19+
20+
* `callback` - callback function with first parameter as error and second parameter as string for code snippet
21+
22+
##### Example:
23+
```js
24+
var request = new sdk.Request('www.google.com'), //using postman sdk to create request
25+
options = {
26+
indentCount: 3,
27+
indentType: 'Space',
28+
requestTimeout: 200,
29+
trimRequestBody: true
30+
};
31+
convert(request, options, function(error, snippet) {
32+
if (error) {
33+
// handle error
34+
}
35+
// handle snippet
36+
});
37+
```
38+
### Guidelines for using generated snippet
39+
40+
* Since Postman-SDK Request object doesn't provide complete path of the file, it needs to be manually inserted in case of uploading a file.
41+
42+
* This module doesn't support cookies.

codegens/nodejs-axios/codesnippet.js

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
var axios = require('axios'),
2+
qs = require('qs');
3+
4+
var config = {
5+
'headers': {
6+
}
7+
}
8+
9+
axios.get('https://mockbin.org/redirect/302/1/?to=https://postman-echo.com/get', config).then((response) => {
10+
console.log(JSON.stringify(response.data));
11+
}).catch((err) => {
12+
console.log(err);
13+
});

codegens/nodejs-axios/index.js

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
module.exports = require('./lib');

codegens/nodejs-axios/lib/axios.js

+184
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
var _ = require('./lodash'),
2+
3+
parseRequest = require('./parseRequest'),
4+
sanitize = require('./util').sanitize,
5+
sanitizeOptions = require('./util').sanitizeOptions;
6+
7+
/**
8+
* returns snippet of nodejs(request) by parsing data from Postman-SDK request object
9+
*
10+
* @param {Object} request - Postman SDK request object
11+
* @param {String} indentString - indentation required for code snippet
12+
* @param {Object} options
13+
* @returns {String} - nodejs(request) code snippet for given request object
14+
*/
15+
function makeSnippet (request, indentString, options) {
16+
var snippet,
17+
optionsArrayBody = [],
18+
optionsArrayConfig = [],
19+
bodyFeild = null,
20+
headerFeild = null,
21+
isFormDataFile = false;
22+
if (options.ES6_enabled) {
23+
snippet = 'const ';
24+
}
25+
else {
26+
snippet = 'var ';
27+
}
28+
snippet += 'axios = require(\'axios\'),\n';
29+
snippet += ' qs = require(\'qs\');\n\n';
30+
if (request.body && request.body.mode === 'formdata') {
31+
_.forEach(request.body.toJSON().formdata, function (data) {
32+
if (!data.disabled && data.type === 'file') {
33+
isFormDataFile = true;
34+
}
35+
});
36+
}
37+
if (isFormDataFile) {
38+
if (options.ES6_enabled) {
39+
snippet += 'const ';
40+
}
41+
else {
42+
snippet += 'var ';
43+
}
44+
snippet += 'fs = require(\'fs\');\n\n';
45+
}
46+
47+
if (request.body && !request.headers.has('Content-Type')) {
48+
if (request.body.mode === 'file') {
49+
request.addHeader({
50+
key: 'Content-Type',
51+
value: 'text/plain'
52+
});
53+
}
54+
else if (request.body.mode === 'graphql') {
55+
request.addHeader({
56+
key: 'Content-Type',
57+
value: 'application/json'
58+
});
59+
}
60+
}
61+
62+
// setting up body for axios
63+
if (request.method === 'PUT' || request.method === 'POST' || request.method === 'PATCH') {
64+
if (request.body && request.body[request.body.mode]) {
65+
optionsArrayBody.push(
66+
parseRequest.parseBody(request.body.toJSON(), indentString, options.trimRequestBody,
67+
request.headers.get('Content-Type'))
68+
);
69+
bodyFeild = optionsArrayBody.join(',\n') + '\n';
70+
}
71+
}
72+
snippet += bodyFeild ? 'var body = ' + bodyFeild + '\n' : '';
73+
74+
// setting up headers(config) for axios
75+
if (options.requestTimeout) {
76+
optionsArrayConfig.push(indentString + `timeout: ${options.requestTimeout}`);
77+
}
78+
if (options.followRedirect === false) {
79+
optionsArrayConfig.push(indentString + 'followRedirect: false');
80+
}
81+
optionsArrayConfig.push(parseRequest.parseHeader(request, indentString));
82+
83+
headerFeild = optionsArrayConfig.join(',\n');
84+
snippet += headerFeild ? 'var config = {\n' + headerFeild + '\n}\n\n' : '';
85+
86+
// framming axios request
87+
snippet += `axios.${request.method.toLowerCase()}('${sanitize(request.url.toString())}', `;
88+
snippet += bodyFeild ? 'body, ' : '';
89+
snippet += headerFeild ? 'config' : '';
90+
snippet += ').then((response) => {\n';
91+
// snippet += 'var body = await JSON.stringify(res.data.body);';
92+
snippet += '\tconsole.log(JSON.stringify(response.data));\n';
93+
snippet += '}).catch((err) => {\n';
94+
snippet += '\tconsole.log(err);\n';
95+
snippet += '});\n';
96+
console.log('----snippet--- \n' + snippet + '\n-----snippet----\n');
97+
return snippet;
98+
}
99+
100+
/**
101+
* Used to get the options specific to this codegen
102+
*
103+
* @returns {Array} - Returns an array of option objects
104+
*/
105+
function getOptions () {
106+
return [{
107+
name: 'Set indentation count',
108+
id: 'indentCount',
109+
type: 'positiveInteger',
110+
default: 2,
111+
description: 'Set the number of indentation characters to add per code level'
112+
},
113+
{
114+
name: 'Set indentation type',
115+
id: 'indentType',
116+
type: 'enum',
117+
availableOptions: ['Tab', 'Space'],
118+
default: 'Space',
119+
description: 'Select the character used to indent lines of code'
120+
},
121+
{
122+
name: 'Set request timeout',
123+
id: 'requestTimeout',
124+
type: 'positiveInteger',
125+
default: 0,
126+
description: 'Set number of milliseconds the request should wait for a response' +
127+
' before timing out (use 0 for infinity)'
128+
},
129+
{
130+
name: 'Follow redirects',
131+
id: 'followRedirect',
132+
type: 'boolean',
133+
default: true,
134+
description: 'Automatically follow HTTP redirects'
135+
},
136+
{
137+
name: 'Trim request body fields',
138+
id: 'trimRequestBody',
139+
type: 'boolean',
140+
default: false,
141+
description: 'Remove white space and additional lines that may affect the server\'s response'
142+
},
143+
{
144+
name: 'Enable ES6 features',
145+
id: 'ES6_enabled',
146+
type: 'boolean',
147+
default: false,
148+
description: 'Modifies code snippet to incorporate ES6 (EcmaScript) features'
149+
}
150+
];
151+
}
152+
153+
/**
154+
* Converts Postman sdk request object to nodejs request code snippet
155+
*
156+
* @param {Object} request - postman-SDK request object
157+
* @param {Object} options
158+
* @param {String} options.indentType - type for indentation eg: Space, Tab
159+
* @param {String} options.indentCount - number of spaces or tabs for indentation.
160+
* @param {Boolean} options.followRedirect - whether to enable followredirect
161+
* @param {Boolean} options.trimRequestBody - whether to trim fields in request body or not
162+
* @param {Boolean} options.ES6_enabled - whether to generate snippet with ES6 features
163+
* @param {Number} options.requestTimeout : time in milli-seconds after which request will bail out
164+
* @param {Function} callback - callback function with parameters (error, snippet)
165+
*/
166+
function convert (request, options, callback) {
167+
if (!_.isFunction(callback)) {
168+
throw new Error('NodeJS-Request-Converter: callback is not valid function');
169+
}
170+
options = sanitizeOptions(options, getOptions());
171+
172+
// String representing value of indentation required
173+
var indentString;
174+
175+
indentString = options.indentType === 'Tab' ? '\t' : ' ';
176+
indentString = indentString.repeat(options.indentCount);
177+
178+
return callback(null, makeSnippet(request, indentString, options));
179+
}
180+
181+
module.exports = {
182+
convert: convert,
183+
getOptions: getOptions
184+
};

codegens/nodejs-axios/lib/index.js

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
module.exports = {
2+
convert: require('./axios').convert,
3+
getOptions: require('./axios').getOptions
4+
};

0 commit comments

Comments
 (0)