Skip to content

#46 - Support transforming swagger variable names to specified Postma… #47

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

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
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
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
# Idea
.idea/

#VS Code
.vscode

#################
## npm
#################

npm-debug.log
node_modules/

53 changes: 51 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,5 +55,54 @@ var options = {
var swaggerConverter = new Swagger2Postman(options);
```

**valid options are:**
includeQueryParams - (default true) Include query string parameters in the request url.
**Valid options are:**

* includeQueryParams - (default true) Include query string parameters in the request url.
* transforms - (default empty) Map used to transform Swagger variables to differently named Postman variables. See [Transforms](#transforms) section below for details.

**Transforms**

```js
this.options = {
transforms: {
header: {
'<SWAGGER HEADER NAME>': '<POSTMAN REPLACEMENT>',
}, path: {
'<SWAGGER PATH VARIABLE NAME>': '<POSTMAN REPLACEMENT>',
}, formData: {
'<SWAGGER FORMDATA VARIABLE NAME>': '<POSTMAN REPLACEMENT>',
}, body: {
'<SWAGGER BODY VARIABLE NAME>': '<POSTMAN REPLACEMENT>',
}
}
}
```

The <POSTMAN REPLACEMENT> must contain the wrapping double-curly braces ({{...}}). The <POSTMAN REPLACEMENT> may contain any other hardcoded text/values as well. For instance, a common need for this is setting an Authorization HTTP header, that requires a Bearer prefix, for example:

```js
this.options = {
transforms: {
header: {
'Authorization': 'Bearer {{ACCESS_TOKEN}}'
}
}
}
```

An example initializing the Swagger2Postman converter w/ transform parameters is as follows:

```js
converter = new Swagger2Postman({
includeQueryParams: false,
transforms: {
header: {
'api-key': '{{API_KEY}}',
'Authorization': 'Bearer {{ACCESS_TOKEN}}',
},
path: {
'ownerId': '{{OWNER_ID}}'
}
}
});
```
55 changes: 39 additions & 16 deletions convert.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ var uuidv4 = require('uuid/v4'),
};

this.options = options || {};
this.transforms = this.options.transforms || {};

this.options.includeQueryParams = typeof (this.options.includeQueryParams) == 'undefined' ?
true : this.options.includeQueryParams;
Expand Down Expand Up @@ -55,6 +56,29 @@ var uuidv4 = require('uuid/v4'),
return new ConvertResult('passed', '');
},

transformParameter: function (parameter, transforms) {
transforms = transforms || {};

if (parameter in transforms) {
return transforms[parameter];
}
else {
return '{{' + parameter + '}}';
}
},

getPostmanVariable: function (thisParams, param, transforms) {
var postmanVariableName = this.transformParameter(thisParams[param].name, transforms),
// Get default value for .in = query/header/path/formData
defaultVal = postmanVariableName;

if (thisParams[param].hasOwnProperty('default')) {
defaultVal = thisParams[param].default;
}

return defaultVal;
},

setBasePath: function (json) {
this.basePath = '';
if (json.host) {
Expand Down Expand Up @@ -193,10 +217,10 @@ var uuidv4 = require('uuid/v4'),
hasQueryParams = false,
param,
requestAttr,
defaultVal,
thisConsumes = root.globalConsumes,
thisProduces = root.globalProduces,
tempBasePath;
tempBasePath,
transforms = this.options.transforms || {};

if (path.length > 0 && path[0] === '/') {
path = path.substring(1);
Expand Down Expand Up @@ -254,29 +278,27 @@ var uuidv4 = require('uuid/v4'),
if (thisParams.hasOwnProperty(param) && thisParams[param]) {
this.logger('Processing param: ' + JSON.stringify(param));

// Get default value for .in = query/header/path/formData
defaultVal = '{{' + thisParams[param].name + '}}';
if (thisParams[param].hasOwnProperty('default')) {
defaultVal = thisParams[param].default;
}

if (thisParams[param].in === 'query' && this.options.includeQueryParams !== false) {
if (!hasQueryParams) {
hasQueryParams = true;
request.url += '?';
}
request.url += thisParams[param].name + '=' + defaultVal + '&';
}

request.url += thisParams[param].name +
'=' +
this.getPostmanVariable(thisParams, param, transforms.query) +
'&';
}
else if (thisParams[param].in === 'header') {
request.headers += thisParams[param].name + ': ' + defaultVal + '\n';
request.headers += thisParams[param].name +
': ' +
this.getPostmanVariable(thisParams, param, transforms.header) +
'\n';
}

else if (thisParams[param].in === 'body') {
request.dataMode = 'raw';
request.rawModeData = thisParams[param].description;
request.rawModeData = this.getPostmanVariable(thisParams, param, transforms.body);
}

else if (thisParams[param].in === 'formData') {
if (thisConsumes.indexOf('application/x-www-form-urlencoded') > -1) {
request.dataMode = 'urlencoded';
Expand All @@ -286,7 +308,7 @@ var uuidv4 = require('uuid/v4'),
}
request.data.push({
'key': thisParams[param].name,
'value': defaultVal,
'value': this.getPostmanVariable(thisParams, param, transforms.formData),
'type': 'text',
'enabled': true
});
Expand All @@ -295,7 +317,8 @@ var uuidv4 = require('uuid/v4'),
if (!request.hasOwnProperty('pathVariables')) {
request.pathVariables = {};
}
request.pathVariables[thisParams[param].name] = defaultVal;
request.pathVariables[thisParams[param].name] =
this.getPostmanVariable(thisParams, param, transforms.path);
}
}
}
Expand Down
25 changes: 24 additions & 1 deletion test/converter-spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ describe('the converter', function () {
expect(convertWithoutOptionsResult.collection.requests[3].url.indexOf('{') > 0).to.be(true);
});

it('should convert path paramters to postman-compatible paramters', function () {
it('should convert path parameters to postman-compatible parameters', function () {
var samplePath = path.join(__dirname, 'data', 'swagger2-with-params.json'),
swagger = require(samplePath),
converter = new Swagger2Postman(),
Expand All @@ -66,4 +66,27 @@ describe('the converter', function () {
expect(convertResult.collection.requests[0].url.indexOf(':ownerId') > -1).to.be(true);
expect(convertResult.collection.requests[0].url.indexOf(':petId') > -1).to.be(true);
});

it('should transform parameters based on options.transforms', function () {
var samplePath = path.join(__dirname, 'data', 'swagger2-with-transformed-params.json'),
swagger = require(samplePath),
converter = new Swagger2Postman({
transforms: {
header: {
'api-key': '{{API_KEY}}',
'Authorization': 'Bearer {{ACCESS_TOKEN}}',
'withDefaultValue': '{{WITH_DEFAULT_VALUE}}'
},
path: {
'ownerId': '{{OWNER_ID}}'
}
}
}),
convertResult = converter.convert(swagger);

expect(convertResult.collection.requests[0].pathVariables.ownerId).to.be('{{OWNER_ID}}');
expect(convertResult.collection.requests[0].pathVariables.petId).to.be('{{petId}}');
expect(convertResult.collection.requests[0].headers).to.be(
'api-key: {{API_KEY}}\nAuthorization: Bearer {{ACCESS_TOKEN}}\nwithDefaultValue: 42\n');
});
});
65 changes: 65 additions & 0 deletions test/data/swagger2-with-transformed-params.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
{
"swagger": "2.0",
"info": {
"description": "My API",
"version": "1.0.0",
"title": "Awesome Pets API",
"termsOfService": "http://www.domain.com",
"contact": {
"name": "[email protected]"
}
},
"basePath": "/",
"schemes": [
"http"
],
"paths": {
"/owner/{ownerId}/pet/{petId}": {
"post": {
"summary": "Find pets belonging to a owner",
"description": "",
"operationId": "findPetsOfOwners",
"parameters": [{
"in": "path",
"name": "ownerId",
"description": "Should be transformed to Postman variable: {{OWNER_ID}}",
"required": true,
"type": "integer"
}, {
"in": "path",
"name": "petId",
"description": "Do NOT transform! Postman variable: {{petId}}",
"required": true,
"type": "integer"
}, {
"in": "header",
"name": "api-key",
"description": "Transform to Postman variable: {{API_KEY}}",
"required": true,
"type": "string"
}, {
"in": "header",
"name": "Authorization",
"description": "Transform to Postman variable: Bearer {{ACCESS_TOKEN}}",
"required": true,
"type": "string"
}, {
"in": "header",
"name": "withDefaultValue",
"description": "Should inject the default value and not any variable: 42",
"required": true,
"type": "integer",
"default": 42
}],
"responses": {
"200": {
"description": "Pet found successfully.",
"schema": {
"$ref": "#/definitions/Pet"
}
}
}
}
}
}
}