Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,8 @@ public void processOpts() {
typeMapping.put("double", "Number");
typeMapping.put("number", "Number");
typeMapping.put("DateTime", "Date");
// binary not supported in JavaScript client right now, using String as a workaround
typeMapping.put("binary", "String");

importMapping.clear();
}
Expand Down Expand Up @@ -205,6 +207,7 @@ public void preprocessSwagger(Swagger swagger) {

supportingFiles.add(new SupportingFile("package.mustache", "", "package.json"));
supportingFiles.add(new SupportingFile("index.mustache", sourceFolder, "index.js"));
supportingFiles.add(new SupportingFile("ApiClient.mustache", sourceFolder, "ApiClient.js"));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['superagent'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('superagent'));
} else {
// Browser globals (root is window)
if (!root.{{moduleName}}) {
root.{{moduleName}} = {};
}
root.{{moduleName}}.ApiClient = factory(root.superagent);
}
}(this, function(superagent) {
'use strict';

var ApiClient = function ApiClient() {
this.basePath = '{{basePath}}'.replace(/\/+$/, '');
};

ApiClient.prototype.paramToString = function paramToString(param) {
if (param == null) {
// return empty string for null and undefined
return '';
} else {
return param.toString();
}
};

/**
* Build full URL by appending the given path to base path and replacing
* path parameter placeholders with parameter values.
* NOTE: query parameters are not handled here.
*/
ApiClient.prototype.buildUrl = function buildUrl(path, pathParams) {
if (!path.match(/^\//)) {
path = '/' + path;
}
var url = this.basePath + path;
var _this = this;
url = url.replace(/\{([\w-]+)\}/g, function(fullMatch, key) {
var value;
if (pathParams.hasOwnProperty(key)) {
value = _this.paramToString(pathParams[key]);
} else {
value = fullMatch;
}
return encodeURIComponent(value);
});
return url;
};

/**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
* application/json
* application/json; charset=UTF8
* APPLICATION/JSON
*/
ApiClient.prototype.isJsonMime = function isJsonMime(mime) {
return Boolean(mime != null && mime.match(/^application\/json(;.*)?$/i));
};

/**
* Choose a MIME from the given MIMEs with JSON preferred,
* i.e. return JSON if included, otherwise return the first one.
*/
ApiClient.prototype.jsonPreferredMime = function jsonPreferredMime(mimes) {
var len = mimes.length;
for (var i = 0; i < len; i++) {
if (this.isJsonMime(mimes[i])) {
return mimes[i];
}
}
return mimes[0];
};

/**
* Normalize parameters values:
* remove nils,
* keep files and arrays,
* format to string with `paramToString` for other cases.
*/
ApiClient.prototype.normalizeParams = function normalizeParams(params) {
var newParams = {};
for (var key in params) {
if (params.hasOwnProperty(key) && params[key] != null) {
var value = params[key];
if (value instanceof Blob || Array.isArray(value)) {
newParams[key] = value;
} else {
newParams[key] = this.paramToString(value);
}
}
}
return newParams;
};

ApiClient.prototype.callApi = function callApi(path, httpMethod, pathParams,
queryParams, headerParams, formParams, bodyParam, contentTypes, accepts,
callback) {
var url = this.buildUrl(path, pathParams);
var request = superagent(httpMethod, url);

// set query parameters
request.query(this.normalizeParams(queryParams));

// set header parameters
request.set(this.normalizeParams(headerParams));

var contentType = this.jsonPreferredMime(contentTypes) || 'application/json';
request.type(contentType);

if (contentType === 'application/x-www-form-urlencoded') {
request.send(this.normalizeParams(formParams));
} else if (contentType == 'multipart/form-data') {
var _formParams = this.normalizeParams(formParams);
for (var key in _formParams) {
if (_formParams.hasOwnProperty(key)) {
if (_formParams[key] instanceof Blob) {
// file field
request.attach(key, _formParams[key]);
} else {
request.field(key, _formParams[key]);
}
}
}
} else if (bodyParam) {
request.send(bodyParam);
}

var accept = this.jsonPreferredMime(accepts);
if (accept) {
request.accept(accept);
}

request.end(function(error, response) {
if (callback) {
var data = response && response.body;
callback(error, data, response);
}
});

return request;
};

ApiClient.default = new ApiClient();

return ApiClient;
}));
191 changes: 76 additions & 115 deletions modules/swagger-codegen/src/main/resources/Javascript/api.mustache
Original file line number Diff line number Diff line change
@@ -1,125 +1,86 @@
// require files in Node.js environment
var ${{#imports}}, {{import}}{{/imports}};
if (typeof module === 'object' && module.exports) {
$ = require('jquery');{{#imports}}
{{import}} = require('../model/{{import}}.js');{{/imports}}
}

// export module for AMD
if ( typeof define === "function" && define.amd ) {
define(['jquery'{{#imports}}, '{{import}}'{{/imports}}], function(${{#imports}}, {{import}}{{/imports}}) {
return {{classname}};
});
}

var {{classname}} = function {{classname}}() {
var self = this;
{{#operations}}
{{#operation}}
/**
* {{summary}}
* {{notes}}
{{#allParams}} * @param {{=<% %>=}}{<% dataType %>} <%={{ }}=%> {{paramName}} {{description}}
{{/allParams}} * @param {function} callback the callback function
* @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
*/
self.{{nickname}} = function({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}callback) {
var {{localVariablePrefix}}postBody = {{#bodyParam}}{{^isBinary}}JSON.stringify({{paramName}}){{/isBinary}}{{#isBinary}}null{{/isBinary}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
var {{localVariablePrefix}}postBinaryBody = {{#bodyParam}}{{#isBinary}}{{paramName}}{{/isBinary}}{{^isBinary}}null{{/isBinary}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
{{#allParams}}{{#required}}
// verify the required parameter '{{paramName}}' is set
if ({{paramName}} == null) {
//throw new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{nickname}}");
var errorRequiredMsg = "Missing the required parameter '{{paramName}}' when calling {{nickname}}";
throw errorRequiredMsg;
}
{{/required}}{{/allParams}}
// create path and map variables
var basePath = '{{basePath}}';
// if basePath ends with a /, remove it as path starts with a leading /
if (basePath.substring(basePath.length-1, basePath.length)=='/') {
basePath = basePath.substring(0, basePath.length-1);
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['../ApiClient'{{#imports}}, '../model/{{import}}'{{/imports}}], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient'){{#imports}}, require('../model/{{import}}'){{/imports}});
} else {
// Browser globals (root is window)
if (!root.{{moduleName}}) {
root.{{moduleName}} = {};
}

var {{localVariablePrefix}}path = basePath + replaceAll(replaceAll("{{{path}}}", "\\{format\\}","json"){{#pathParams}}
, "\\{" + "{{baseName}}" + "\\}", encodeURIComponent({{{paramName}}}.toString()){{/pathParams}});
root.{{moduleName}}.{{classname}} = factory(root.{{moduleName}}.ApiClient{{#imports}}, root.{{moduleName}}.{{import}}{{/imports}});
}
}(this, function(ApiClient{{#imports}}, {{import}}{{/imports}}) {
'use strict';

var queryParams = {};
var headerParams = {};
var formParams = {};
var {{classname}} = function {{classname}}(apiClient) {
this.apiClient = apiClient || ApiClient.default;

{{#queryParams}}
queryParams.{{baseName}} = {{paramName}};
{{/queryParams}}
{{#headerParams}}if ({{paramName}} != null)
{{localVariablePrefix}}headerParams.put("{{baseName}}", {{paramName}});
{{/headerParams}}
{{#formParams}}if ({{paramName}} != null)
{{localVariablePrefix}}formParams.put("{{baseName}}", {{paramName}});
{{/formParams}}
var self = this;
{{#operations}}
{{#operation}}
/**
* {{summary}}
* {{notes}}
{{#allParams}} * @param {{=<% %>=}}{<% dataType %>} <%={{ }}=%> {{paramName}} {{description}}
{{/allParams}} * @param {function} callback the callback function, accepting three arguments: error, data, response{{#returnType}}
* data is of type: {{{returnType}}}{{/returnType}}
*/
self.{{nickname}} = function({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}callback) {
var postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
{{#allParams}}{{#required}}
// verify the required parameter '{{paramName}}' is set
if ({{paramName}} == null) {
throw "Missing the required parameter '{{paramName}}' when calling {{nickname}}";
}
{{/required}}{{/allParams}}

path += createQueryString(queryParams);
{{=< >=}}
var pathParams = {<#pathParams>
'<baseName>': <paramName><#hasMore>,</hasMore></pathParams>
};
var queryParams = {<#queryParams>
'<baseName>': <paramName><#hasMore>,</hasMore></queryParams>
};
var headerParams = {<#headerParams>
'<baseName>': <paramName><#hasMore>,</hasMore></headerParams>
};
var formParams = {<#formParams>
'<baseName>': <paramName><#hasMore>,</hasMore></formParams>
};

var options = {type: "{{httpMethod}}", async: true, contentType: "application/json", dataType: "json", data: postBody};
var request = $.ajax(path, options);
var contentTypes = [<#consumes>'<mediaType>'<#hasMore>, </hasMore></consumes>];
var accepts = [<#produces>'<mediaType>'<#hasMore>, </hasMore></produces>];

request.fail(function(jqXHR, textStatus, errorThrown){
if (callback) {
var error = errorThrown || textStatus || jqXHR.statusText || 'error';
callback(null, textStatus, jqXHR, error);
}
});

request.done(function(response, textStatus, jqXHR){
{{#returnType}}
/**
* @returns {{{returnType}}}
*/
{{#returnTypeIsPrimitive}}var myResponse = response;{{/returnTypeIsPrimitive}}
{{^returnTypeIsPrimitive}}var myResponse = new {{{returnType}}}();
myResponse.constructFromObject(response);{{/returnTypeIsPrimitive}}
var handleResponse = null;
if (callback) {
callback(myResponse, textStatus, jqXHR);
handleResponse = function(error, data, response) {<#returnType><#returnTypeIsPrimitive>
callback(error, data, response);</returnTypeIsPrimitive><^returnTypeIsPrimitive><#isListContainer>
// TODO: support deserializing array of models
callback(error, data, response);</isListContainer><^isListContainer>
if (!error && data) {
var result = new <&returnType>();
result.constructFromObject(data);
callback(error, result, response);
} else {
callback(error, data, response);
}</isListContainer></returnTypeIsPrimitive></returnType><^returnType>
callback(error, data, response);</returnType>
};
}
{{/returnType}}{{^returnType}}
if (callback) {
callback(response, textStatus, jqXHR);
}
{{/returnType}}
});

return request;
}
{{/operation}}
{{/operations}}

function replaceAll (haystack, needle, replace) {
var result= haystack;
if (needle !=null && replace!=null) {
result= haystack.replace(new RegExp(needle, 'g'), replace);
}
return result;
}

function createQueryString (queryParams) {
var queryString ='';
var i = 0;
for (var queryParamName in queryParams) {
if (i==0) {
queryString += '?' ;
} else {
queryString += '&' ;
}

queryString += queryParamName + '=' + encodeURIComponent(queryParams[queryParamName]);
i++;
}

return queryString;
}
}
return this.apiClient.callApi(
'<&path>', '<httpMethod>',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, handleResponse
);
<={{ }}=>
}
{{/operation}}
{{/operations}}
};

// export module for Node.js
if (typeof module === 'object' && module.exports) {
module.exports = {{classname}};
}
return {{classname}};
}));
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
if (typeof module === 'object' && module.exports) {
var {{moduleName}} = {};
{{#models}}
{{moduleName}}.{{importPath}} = require('./model/{{importPath}}.js');
{{/models}}
{{#apiInfo}}{{#apis}}
{{moduleName}}.{{importPath}} = require('./api/{{importPath}}.js');
{{/apis}}{{/apiInfo}}
module.exports = {{moduleName}};
}
(function(factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['./ApiClient'{{#models}}, './model/{{importPath}}'{{/models}}{{#apiInfo}}{{#apis}}, './api/{{importPath}}'{{/apis}}{{/apiInfo}}], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('./ApiClient'){{#models}}, require('./model/{{importPath}}'){{/models}}{{#apiInfo}}{{#apis}}, require('./api/{{importPath}}'){{/apis}}{{/apiInfo}});
}
}(function(ApiClient{{#models}}, {{importPath}}{{/models}}{{#apiInfo}}{{#apis}}, {{importPath}}{{/apis}}{{/apiInfo}}) {
'use strict';

return {
ApiClient: ApiClient{{#models}},
{{importPath}}: {{importPath}}{{/models}}{{#apiInfo}}{{#apis}},
{{importPath}}: {{importPath}}{{/apis}}{{/apiInfo}}
};
}));
Loading