Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Adds nodejs-axios codegen #245

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion codegens/java-okhttp/test/newman/newman.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ describe('convert for different request types', function () {
testConfig = {
compileScript: 'javac -cp *: main.java',
runScript: 'java -cp *: main',
fileName: 'main.java'
fileName: 'main.java',
skipCollections: ['redirectCollection']
};
runNewmanTest(convert, options, testConfig);
});
41 changes: 41 additions & 0 deletions codegens/nodejs-axios/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
.DS_Store
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Coverage directory used by tools like istanbul
.coverage

# node-waf configuration
.lock-wscript


# Dependency directories
node_modules/
jspm_packages/

# Typescript v1 declaration files
typings/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env

out/
76 changes: 76 additions & 0 deletions codegens/nodejs-axios/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
### NPM Specific: Disregard recursive project files
### ===============================================
/.editorconfig
/.gitmodules
/test

### Borrowed from .gitignore
### ========================

# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Prevent IDE stuff
.idea
.vscode
*.sublime-*

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
.coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Typescript v1 declaration files
typings/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env

snippet.swift

out/
42 changes: 42 additions & 0 deletions codegens/nodejs-axios/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@

> Converts Postman-SDK Request into code snippet for .

#### Prerequisites
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.

## Using the Module
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.

### convert function
Convert function takes three parameters

* `request` - Postman-SDK Request Object

* `options` - options is an object which hsa following properties
* `indentType` - String denoting type of indentation for code snippet. eg: 'Space', 'Tab'
* `indentCount` - The number of indentation characters to add per code level
* `trimRequestBody` - Whether or not request body fields should be trimmed

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

##### Example:
```js
var request = new sdk.Request('www.google.com'), //using postman sdk to create request
options = {
indentCount: 3,
indentType: 'Space',
requestTimeout: 200,
trimRequestBody: true
};
convert(request, options, function(error, snippet) {
if (error) {
// handle error
}
// handle snippet
});
```
### Guidelines for using generated snippet

* 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.

* This module doesn't support cookies.
1 change: 1 addition & 0 deletions codegens/nodejs-axios/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = require('./lib');
184 changes: 184 additions & 0 deletions codegens/nodejs-axios/lib/axios.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
var _ = require('./lodash'),

parseRequest = require('./parseRequest'),
sanitize = require('./util').sanitize,
sanitizeOptions = require('./util').sanitizeOptions;

/**
* returns snippet of nodejs(request) by parsing data from Postman-SDK request object
*
* @param {Object} request - Postman SDK request object
* @param {String} indentString - indentation required for code snippet
* @param {Object} options
* @returns {String} - nodejs(request) code snippet for given request object
*/
function makeSnippet (request, indentString, options) {
var snippet,
optionsArrayBody = [],
optionsArrayConfig = [],
bodyFeild = null,
headerFeild = null,
isFormDataFile = false;
if (options.ES6_enabled) {
snippet = 'const ';
}
else {
snippet = 'var ';
}
snippet += 'axios = require(\'axios\'),\n';
snippet += ' qs = require(\'qs\');\n\n';
if (request.body && request.body.mode === 'formdata') {
_.forEach(request.body.toJSON().formdata, function (data) {
if (!data.disabled && data.type === 'file') {
isFormDataFile = true;
}
});
}
if (isFormDataFile) {
if (options.ES6_enabled) {
snippet += 'const ';
}
else {
snippet += 'var ';
}
snippet += 'fs = require(\'fs\');\n\n';
}

if (request.body && !request.headers.has('Content-Type')) {
if (request.body.mode === 'file') {
request.addHeader({
key: 'Content-Type',
value: 'text/plain'
});
}
else if (request.body.mode === 'graphql') {
request.addHeader({
key: 'Content-Type',
value: 'application/json'
});
}
}

// setting up body for axios
if (request.method === 'PUT' || request.method === 'POST' || request.method === 'PATCH') {
if (request.body && request.body[request.body.mode]) {
optionsArrayBody.push(
parseRequest.parseBody(request.body.toJSON(), indentString, options.trimRequestBody,
request.headers.get('Content-Type'))
);
bodyFeild = optionsArrayBody.join(',\n') + '\n';
}
}
snippet += bodyFeild ? 'var body = ' + bodyFeild + '\n' : '';

// setting up headers(config) for axios
if (options.requestTimeout) {
optionsArrayConfig.push(indentString + `timeout: ${options.requestTimeout}`);
}
if (options.followRedirect === false) {
optionsArrayConfig.push(indentString + 'followRedirect: false');
}
optionsArrayConfig.push(parseRequest.parseHeader(request, indentString));

headerFeild = optionsArrayConfig.join(',\n');
snippet += headerFeild ? 'var config = {\n' + headerFeild + '\n}\n\n' : '';

// framming axios request
snippet += `axios.${request.method.toLowerCase()}('${sanitize(request.url.toString())}', `;
snippet += bodyFeild ? 'body, ' : '';
snippet += headerFeild ? 'config' : '';
snippet += ').then((response) => {\n';
// snippet += 'var body = await JSON.stringify(res.data.body);';
snippet += '\tconsole.log(JSON.stringify(response.data));\n';
snippet += '}).catch((err) => {\n';
snippet += '\tconsole.log(err);\n';
snippet += '});\n';
console.log('----snippet--- \n' + snippet + '\n-----snippet----\n');
return snippet;
}

/**
* Used to get the options specific to this codegen
*
* @returns {Array} - Returns an array of option objects
*/
function getOptions () {
return [{
name: 'Set indentation count',
id: 'indentCount',
type: 'positiveInteger',
default: 2,
description: 'Set the number of indentation characters to add per code level'
},
{
name: 'Set indentation type',
id: 'indentType',
type: 'enum',
availableOptions: ['Tab', 'Space'],
default: 'Space',
description: 'Select the character used to indent lines of code'
},
{
name: 'Set request timeout',
id: 'requestTimeout',
type: 'positiveInteger',
default: 0,
description: 'Set number of milliseconds the request should wait for a response' +
' before timing out (use 0 for infinity)'
},
{
name: 'Follow redirects',
id: 'followRedirect',
type: 'boolean',
default: true,
description: 'Automatically follow HTTP redirects'
},
{
name: 'Trim request body fields',
id: 'trimRequestBody',
type: 'boolean',
default: false,
description: 'Remove white space and additional lines that may affect the server\'s response'
},
{
name: 'Enable ES6 features',
id: 'ES6_enabled',
type: 'boolean',
default: false,
description: 'Modifies code snippet to incorporate ES6 (EcmaScript) features'
}
];
}

/**
* Converts Postman sdk request object to nodejs request code snippet
*
* @param {Object} request - postman-SDK request object
* @param {Object} options
* @param {String} options.indentType - type for indentation eg: Space, Tab
* @param {String} options.indentCount - number of spaces or tabs for indentation.
* @param {Boolean} options.followRedirect - whether to enable followredirect
* @param {Boolean} options.trimRequestBody - whether to trim fields in request body or not
* @param {Boolean} options.ES6_enabled - whether to generate snippet with ES6 features
* @param {Number} options.requestTimeout : time in milli-seconds after which request will bail out
* @param {Function} callback - callback function with parameters (error, snippet)
*/
function convert (request, options, callback) {
if (!_.isFunction(callback)) {
throw new Error('NodeJS-Request-Converter: callback is not valid function');
}
options = sanitizeOptions(options, getOptions());

// String representing value of indentation required
var indentString;

indentString = options.indentType === 'Tab' ? '\t' : ' ';
indentString = indentString.repeat(options.indentCount);

return callback(null, makeSnippet(request, indentString, options));
}

module.exports = {
convert: convert,
getOptions: getOptions
};
4 changes: 4 additions & 0 deletions codegens/nodejs-axios/lib/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = {
convert: require('./axios').convert,
getOptions: require('./axios').getOptions
};
Loading