swagger-client
Advanced tools
Comparing version 1.0.4 to 2.0.0-develop
// Generated by CoffeeScript 1.4.0 | ||
(function() { | ||
var SwaggerApi, SwaggerModel, SwaggerModelProperty, SwaggerOperation, SwaggerRequest, SwaggerResource, | ||
var ApiKeyAuthorization, SwaggerApi, SwaggerAuthorizations, SwaggerHttp, SwaggerModel, SwaggerModelProperty, SwaggerOperation, SwaggerRequest, SwaggerResource, | ||
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; | ||
@@ -8,31 +8,28 @@ | ||
SwaggerApi.prototype.discoveryUrl = "http://api.wordnik.com/v4/resources.json"; | ||
SwaggerApi.prototype.url = "http://api.wordnik.com/v4/resources.json"; | ||
SwaggerApi.prototype.debug = false; | ||
SwaggerApi.prototype.api_key = null; | ||
SwaggerApi.prototype.basePath = null; | ||
function SwaggerApi(options) { | ||
SwaggerApi.prototype.authorizations = null; | ||
SwaggerApi.prototype.authorizationScheme = null; | ||
function SwaggerApi(url, options) { | ||
if (options == null) { | ||
options = {}; | ||
} | ||
if (options.discoveryUrl != null) { | ||
this.discoveryUrl = options.discoveryUrl; | ||
if (url) { | ||
if (url.url) { | ||
options = url; | ||
} else { | ||
this.url = url; | ||
} | ||
} else { | ||
options = url; | ||
} | ||
if (options.debug != null) { | ||
this.debug = options.debug; | ||
if (options.url != null) { | ||
this.url = options.url; | ||
} | ||
this.apiKeyName = options.apiKeyName != null ? options.apiKeyName : 'api_key'; | ||
if (options.apiKey != null) { | ||
this.api_key = options.apiKey; | ||
} | ||
if (options.api_key != null) { | ||
this.api_key = options.api_key; | ||
} | ||
if (options.verbose != null) { | ||
this.verbose = options.verbose; | ||
} | ||
this.supportHeaderParams = options.supportHeaderParams != null ? options.supportHeaderParams : false; | ||
this.supportedSubmitMethods = options.supportedSubmitMethods != null ? options.supportedSubmitMethods : ['get']; | ||
@@ -44,5 +41,3 @@ if (options.success != null) { | ||
this.progress = options.progress != null ? options.progress : function() {}; | ||
this.headers = options.headers != null ? options.headers : {}; | ||
this.booleanValues = options.booleanValues != null ? options.booleanValues : new Array('true', 'false'); | ||
this.discoveryUrl = this.suffixApiKey(this.discoveryUrl); | ||
this.defaultHeaders = options.headers != null ? options.headers : {}; | ||
if (options.success != null) { | ||
@@ -54,60 +49,72 @@ this.build(); | ||
SwaggerApi.prototype.build = function() { | ||
var _this = this; | ||
this.progress('fetching resource list: ' + this.discoveryUrl); | ||
return jQuery.getJSON(this.discoveryUrl, function(response) { | ||
var res, resource, _i, _j, _len, _len1, _ref, _ref1; | ||
if (response.apiVersion != null) { | ||
_this.apiVersion = response.apiVersion; | ||
} | ||
if ((response.basePath != null) && jQuery.trim(response.basePath).length > 0) { | ||
_this.basePath = response.basePath; | ||
if (_this.basePath.match(/^HTTP/i) == null) { | ||
_this.fail("discoveryUrl basePath must be a URL."); | ||
} | ||
_this.basePath = _this.basePath.replace(/\/$/, ''); | ||
} else { | ||
_this.basePath = _this.discoveryUrl.substring(0, _this.discoveryUrl.lastIndexOf('/')); | ||
log('derived basepath from discoveryUrl as ' + _this.basePath); | ||
} | ||
_this.apis = {}; | ||
_this.apisArray = []; | ||
if (response.resourcePath != null) { | ||
_this.resourcePath = response.resourcePath; | ||
res = null; | ||
_ref = response.apis; | ||
for (_i = 0, _len = _ref.length; _i < _len; _i++) { | ||
resource = _ref[_i]; | ||
if (res === null) { | ||
res = new SwaggerResource(resource, _this); | ||
var obj, | ||
_this = this; | ||
this.progress('fetching resource list: ' + this.url); | ||
console.log('getting ' + this.url); | ||
obj = { | ||
url: this.url, | ||
method: "get", | ||
on: { | ||
error: function(response) { | ||
if (_this.url.substring(0, 4) !== 'http') { | ||
return _this.fail('Please specify the protocol for ' + _this.url); | ||
} else if (error.status === 0) { | ||
return _this.fail('Can\'t read from server. It may not have the appropriate access-control-origin settings.'); | ||
} else if (error.status === 404) { | ||
return _this.fail('Can\'t read swagger JSON from ' + _this.url); | ||
} else { | ||
res.addOperations(resource.path, resource.operations); | ||
return _this.fail(error.status + ' : ' + error.statusText + ' ' + _this.url); | ||
} | ||
}, | ||
response: function(rawResponse) { | ||
var api, isApi, newName, operation, res, resource, response, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2; | ||
response = JSON.parse(rawResponse.content.data); | ||
if (response.apiVersion != null) { | ||
_this.apiVersion = response.apiVersion; | ||
} | ||
_this.apis = {}; | ||
_this.apisArray = []; | ||
isApi = false; | ||
_ref = response.apis; | ||
for (_i = 0, _len = _ref.length; _i < _len; _i++) { | ||
api = _ref[_i]; | ||
if (api.operations) { | ||
_ref1 = api.operations; | ||
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { | ||
operation = _ref1[_j]; | ||
isApi = true; | ||
} | ||
} | ||
} | ||
if (isApi) { | ||
newName = response.resourcePath.replace(/\//g, ''); | ||
_this.resourcePath = response.resourcePath; | ||
res = new SwaggerResource(response, _this); | ||
_this.apis[newName] = res; | ||
_this.apisArray.push(res); | ||
} else { | ||
if (response.basePath) { | ||
_this.basePath = response.basePath; | ||
} else if (_this.url.indexOf('?') > 0) { | ||
_this.basePath = _this.url.substring(0, _this.url.lastIndexOf('?')); | ||
} else { | ||
_this.basePath = _this.url; | ||
} | ||
_ref2 = response.apis; | ||
for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { | ||
resource = _ref2[_k]; | ||
res = new SwaggerResource(resource, _this); | ||
_this.apis[res.name] = res; | ||
_this.apisArray.push(res); | ||
} | ||
} | ||
if (_this.success) { | ||
_this.success(); | ||
} | ||
return _this; | ||
} | ||
if (res != null) { | ||
_this.apis[res.name] = res; | ||
_this.apisArray.push(res); | ||
res.ready = true; | ||
_this.selfReflect(); | ||
} | ||
} else { | ||
_ref1 = response.apis; | ||
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { | ||
resource = _ref1[_j]; | ||
res = new SwaggerResource(resource, _this); | ||
_this.apis[res.name] = res; | ||
_this.apisArray.push(res); | ||
} | ||
} | ||
return _this; | ||
}).error(function(error) { | ||
if (_this.discoveryUrl.substring(0, 4) !== 'http') { | ||
return _this.fail('Please specify the protocol for ' + _this.discoveryUrl); | ||
} else if (error.status === 0) { | ||
return _this.fail('Can\'t read from server. It may not have the appropriate access-control-origin settings.'); | ||
} else if (error.status === 404) { | ||
return _this.fail('Can\'t read swagger JSON from ' + _this.discoveryUrl); | ||
} else { | ||
return _this.fail(error.status + ' : ' + error.statusText + ' ' + _this.discoveryUrl); | ||
} | ||
}); | ||
}; | ||
new SwaggerHttp().execute(obj); | ||
return this; | ||
}; | ||
@@ -162,12 +169,2 @@ | ||
SwaggerApi.prototype.suffixApiKey = function(url) { | ||
var sep; | ||
if ((this.api_key != null) && jQuery.trim(this.api_key).length > 0 && (url != null)) { | ||
sep = url.indexOf('?') > 0 ? '&' : '?'; | ||
return url + sep + this.apiKeyName + '=' + this.api_key; | ||
} else { | ||
return url; | ||
} | ||
}; | ||
SwaggerApi.prototype.help = function() { | ||
@@ -199,6 +196,15 @@ var operation, operation_name, parameter, resource, resource_name, _i, _len, _ref, _ref1, _ref2; | ||
SwaggerResource.prototype.api = null; | ||
SwaggerResource.prototype.produces = null; | ||
SwaggerResource.prototype.consumes = null; | ||
function SwaggerResource(resourceObj, api) { | ||
var parts, | ||
var consumes, obj, parts, produces, | ||
_this = this; | ||
this.api = api; | ||
this.api = this.api; | ||
produces = []; | ||
consumes = []; | ||
this.path = this.api.resourcePath != null ? this.api.resourcePath : resourceObj.path; | ||
@@ -213,7 +219,4 @@ this.description = resourceObj.description; | ||
this.models = {}; | ||
if ((resourceObj.operations != null) && (this.api.resourcePath != null)) { | ||
this.api.progress('reading resource ' + this.name + ' models and operations'); | ||
this.addModels(resourceObj.models); | ||
this.addOperations(resourceObj.path, resourceObj.operations); | ||
this.api[this.name] = this; | ||
if ((resourceObj.apis != null) && (this.api.resourcePath != null)) { | ||
this.addApiDeclaration(resourceObj); | ||
} else { | ||
@@ -223,27 +226,46 @@ if (this.path == null) { | ||
} | ||
this.url = this.api.suffixApiKey(this.api.basePath + this.path.replace('{format}', 'json')); | ||
this.url = this.api.basePath + this.path.replace('{format}', 'json'); | ||
this.api.progress('fetching resource ' + this.name + ': ' + this.url); | ||
jQuery.getJSON(this.url, function(response) { | ||
var endpoint, _i, _len, _ref; | ||
if ((response.basePath != null) && jQuery.trim(response.basePath).length > 0) { | ||
_this.basePath = response.basePath; | ||
_this.basePath = _this.basePath.replace(/\/$/, ''); | ||
} | ||
_this.addModels(response.models); | ||
if (response.apis) { | ||
_ref = response.apis; | ||
for (_i = 0, _len = _ref.length; _i < _len; _i++) { | ||
endpoint = _ref[_i]; | ||
_this.addOperations(endpoint.path, endpoint.operations); | ||
obj = { | ||
url: this.url, | ||
method: "get", | ||
on: { | ||
error: function(response) { | ||
return _this.api.fail("Unable to read api '" + _this.name + "' from path " + _this.url + " (server returned " + error.statusText + ")"); | ||
}, | ||
response: function(rawResponse) { | ||
var response; | ||
response = JSON.parse(rawResponse.content.data); | ||
return _this.addApiDeclaration(response); | ||
} | ||
} | ||
_this.api[_this.name] = _this; | ||
_this.ready = true; | ||
return _this.api.selfReflect(); | ||
}).error(function(error) { | ||
return _this.api.fail("Unable to read api '" + _this.name + "' from path " + _this.url + " (server returned " + error.statusText + ")"); | ||
}); | ||
}; | ||
new SwaggerHttp().execute(obj); | ||
} | ||
} | ||
SwaggerResource.prototype.addApiDeclaration = function(response) { | ||
var endpoint, _i, _len, _ref; | ||
if (response.produces != null) { | ||
this.produces = response.produces; | ||
} | ||
if (response.consumes != null) { | ||
this.consumes = response.consumes; | ||
} | ||
if ((response.basePath != null) && response.basePath.replace(/\s/g, '').length > 0) { | ||
this.basePath = response.basePath; | ||
} | ||
this.addModels(response.models); | ||
if (response.apis) { | ||
_ref = response.apis; | ||
for (_i = 0, _len = _ref.length; _i < _len; _i++) { | ||
endpoint = _ref[_i]; | ||
this.addOperations(endpoint.path, endpoint.operations); | ||
} | ||
} | ||
this.api[this.name] = this; | ||
this.ready = true; | ||
return this.api.selfReflect(); | ||
}; | ||
SwaggerResource.prototype.addModels = function(models) { | ||
@@ -270,3 +292,3 @@ var model, modelName, swaggerModel, _i, _len, _ref, _results; | ||
SwaggerResource.prototype.addOperations = function(resource_path, ops) { | ||
var consumes, err, errorResponses, o, op, _i, _j, _len, _len1, _results; | ||
var consumes, method, o, op, produces, responseMessages, _i, _len, _results; | ||
if (ops) { | ||
@@ -276,17 +298,26 @@ _results = []; | ||
o = ops[_i]; | ||
consumes = o.consumes; | ||
consumes = null; | ||
produces = null; | ||
if (o.consumes != null) { | ||
consumes = o.consumes; | ||
} else { | ||
consumes = this.consumes; | ||
} | ||
if (o.produces != null) { | ||
produces = o.produces; | ||
} else { | ||
produces = this.produces; | ||
} | ||
responseMessages = o.responseMessages; | ||
method = o.method; | ||
if (o.httpMethod) { | ||
method = o.httpMethod; | ||
} | ||
if (o.supportedContentTypes) { | ||
consumes = o.supportedContentTypes; | ||
} | ||
errorResponses = o.responseMessages; | ||
if (errorResponses) { | ||
for (_j = 0, _len1 = errorResponses.length; _j < _len1; _j++) { | ||
err = errorResponses[_j]; | ||
err.reason = err.message; | ||
} | ||
} | ||
if (o.errorResponses) { | ||
errorResponses = o.errorResponses; | ||
responseMessages = o.errorResponses; | ||
} | ||
op = new SwaggerOperation(o.nickname, resource_path, o.httpMethod, o.parameters, o.summary, o.notes, o.responseClass, errorResponses, this, o.consumes, o.produces); | ||
op = new SwaggerOperation(o.nickname, resource_path, method, o.parameters, o.summary, o.notes, o.responseClass, responseMessages, this, consumes, produces); | ||
this.operations[op.nickname] = op; | ||
@@ -300,14 +331,16 @@ _results.push(this.operationsArray.push(op)); | ||
SwaggerResource.prototype.help = function() { | ||
var operation, operation_name, parameter, _i, _len, _ref, _ref1; | ||
var msg, operation, operation_name, parameter, _i, _len, _ref, _ref1, _results; | ||
_ref = this.operations; | ||
_results = []; | ||
for (operation_name in _ref) { | ||
operation = _ref[operation_name]; | ||
console.log(" " + operation.nickname); | ||
msg = " " + operation.nickname; | ||
_ref1 = operation.parameters; | ||
for (_i = 0, _len = _ref1.length; _i < _len; _i++) { | ||
parameter = _ref1[_i]; | ||
console.log(" " + parameter.name + (parameter.required ? ' (required)' : '') + " - " + parameter.description); | ||
msg.concat(" " + parameter.name + (parameter.required ? ' (required)' : '') + " - " + parameter.description); | ||
} | ||
_results.push(msg); | ||
} | ||
return this; | ||
return _results; | ||
}; | ||
@@ -459,3 +492,3 @@ | ||
function SwaggerOperation(nickname, path, httpMethod, parameters, summary, notes, responseClass, errorResponses, resource, consumes, produces) { | ||
function SwaggerOperation(nickname, path, method, parameters, summary, notes, responseClass, responseMessages, resource, consumes, produces) { | ||
var parameter, v, _i, _j, _len, _len1, _ref, _ref1, _ref2, | ||
@@ -465,3 +498,3 @@ _this = this; | ||
this.path = path; | ||
this.httpMethod = httpMethod; | ||
this.method = method; | ||
this.parameters = parameters != null ? parameters : []; | ||
@@ -471,3 +504,3 @@ this.summary = summary; | ||
this.responseClass = responseClass; | ||
this.errorResponses = errorResponses; | ||
this.responseMessages = responseMessages; | ||
this.resource = resource; | ||
@@ -484,8 +517,8 @@ this.consumes = consumes; | ||
} | ||
if (this.httpMethod == null) { | ||
this.resource.api.fail("SwaggerOperation " + nickname + " is missing httpMethod."); | ||
if (this.method == null) { | ||
this.resource.api.fail("SwaggerOperation " + nickname + " is missing method."); | ||
} | ||
this.path = this.path.replace('{format}', 'json'); | ||
this.httpMethod = this.httpMethod.toLowerCase(); | ||
this.isGetMethod = this.httpMethod === "get"; | ||
this.method = this.method.toLowerCase(); | ||
this.isGetMethod = this.method === "get"; | ||
this.resourceName = this.resource.name; | ||
@@ -499,3 +532,3 @@ if (((_ref = this.responseClass) != null ? _ref.toLowerCase() : void 0) === 'void') { | ||
} | ||
this.errorResponses = this.errorResponses || []; | ||
this.responseMessages = this.responseMessages || []; | ||
_ref1 = this.parameters; | ||
@@ -540,2 +573,5 @@ for (_i = 0, _len = _ref1.length; _i < _len; _i++) { | ||
}; | ||
this.resource[this.nickname].help = function() { | ||
return _this.help(); | ||
}; | ||
} | ||
@@ -577,12 +613,21 @@ | ||
SwaggerOperation.prototype["do"] = function(args, callback, error) { | ||
var body, headers; | ||
SwaggerOperation.prototype["do"] = function(args, opts, callback, error) { | ||
var key, param, params, possibleParams, req, requestContentType, responseContentType, value; | ||
if (args == null) { | ||
args = {}; | ||
} | ||
if (opts == null) { | ||
opts = {}; | ||
} | ||
requestContentType = null; | ||
responseContentType = null; | ||
if ((typeof args) === "function") { | ||
error = callback; | ||
error = opts; | ||
callback = args; | ||
args = {}; | ||
} | ||
if ((typeof opts) === "function") { | ||
error = callback; | ||
callback = opts; | ||
} | ||
if (error == null) { | ||
@@ -595,14 +640,47 @@ error = function(xhr, textStatus, error) { | ||
callback = function(data) { | ||
return console.log(data); | ||
var content; | ||
content = null; | ||
if (data.content != null) { | ||
content = data.content.data; | ||
} else { | ||
content = "no data"; | ||
} | ||
return console.log("default callback: " + content); | ||
}; | ||
} | ||
params = {}; | ||
if (args.headers != null) { | ||
headers = args.headers; | ||
params.headers = args.headers; | ||
delete args.headers; | ||
} | ||
if (args.body != null) { | ||
body = args.body; | ||
params.body = args.body; | ||
delete args.body; | ||
} | ||
return new SwaggerRequest(this.httpMethod, this.urlify(args), headers, body, callback, error, this); | ||
possibleParams = (function() { | ||
var _i, _len, _ref, _results; | ||
_ref = this.parameters; | ||
_results = []; | ||
for (_i = 0, _len = _ref.length; _i < _len; _i++) { | ||
param = _ref[_i]; | ||
if (param.paramType === "form") { | ||
_results.push(param); | ||
} | ||
} | ||
return _results; | ||
}).call(this); | ||
if (possibleParams) { | ||
for (key in possibleParams) { | ||
value = possibleParams[key]; | ||
if (args[value.name]) { | ||
params[value.name] = args[value.name]; | ||
} | ||
} | ||
} | ||
req = new SwaggerRequest(this.method, this.urlify(args), params, opts, callback, error, this); | ||
if (opts.mock != null) { | ||
return req; | ||
} else { | ||
return true; | ||
} | ||
}; | ||
@@ -618,7 +696,4 @@ | ||
SwaggerOperation.prototype.urlify = function(args, includeApiKey) { | ||
var param, queryParams, reg, url, _i, _len, _ref; | ||
if (includeApiKey == null) { | ||
includeApiKey = true; | ||
} | ||
SwaggerOperation.prototype.urlify = function(args) { | ||
var param, queryParams, reg, url, _i, _j, _len, _len1, _ref, _ref1; | ||
url = this.resource.basePath + this.pathJson(); | ||
@@ -638,10 +713,15 @@ _ref = this.parameters; | ||
} | ||
if (includeApiKey && (this.resource.api.api_key != null) && this.resource.api.api_key.length > 0) { | ||
args[this.apiKeyName] = this.resource.api.api_key; | ||
queryParams = ""; | ||
_ref1 = this.parameters; | ||
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { | ||
param = _ref1[_j]; | ||
if (param.paramType === 'query') { | ||
if (args[param.name]) { | ||
if (queryParams !== "") { | ||
queryParams += "&"; | ||
} | ||
queryParams += encodeURIComponent(param.name) + '=' + encodeURIComponent(args[param.name]); | ||
} | ||
} | ||
} | ||
if (this.supportHeaderParams()) { | ||
queryParams = jQuery.param(this.getQueryParams(args, includeApiKey)); | ||
} else { | ||
queryParams = jQuery.param(this.getQueryAndHeaderParams(args, includeApiKey)); | ||
} | ||
if ((queryParams != null) && queryParams.length > 0) { | ||
@@ -661,24 +741,11 @@ url += "?" + queryParams; | ||
SwaggerOperation.prototype.getQueryAndHeaderParams = function(args, includeApiKey) { | ||
if (includeApiKey == null) { | ||
includeApiKey = true; | ||
} | ||
return this.getMatchingParams(['query', 'header'], args, includeApiKey); | ||
SwaggerOperation.prototype.getQueryParams = function(args) { | ||
return this.getMatchingParams(['query'], args); | ||
}; | ||
SwaggerOperation.prototype.getQueryParams = function(args, includeApiKey) { | ||
if (includeApiKey == null) { | ||
includeApiKey = true; | ||
} | ||
return this.getMatchingParams(['query'], args, includeApiKey); | ||
SwaggerOperation.prototype.getHeaderParams = function(args) { | ||
return this.getMatchingParams(['header'], args); | ||
}; | ||
SwaggerOperation.prototype.getHeaderParams = function(args, includeApiKey) { | ||
if (includeApiKey == null) { | ||
includeApiKey = true; | ||
} | ||
return this.getMatchingParams(['header'], args, includeApiKey); | ||
}; | ||
SwaggerOperation.prototype.getMatchingParams = function(paramTypes, args, includeApiKey) { | ||
SwaggerOperation.prototype.getMatchingParams = function(paramTypes, args) { | ||
var matchingParams, name, param, value, _i, _len, _ref, _ref1; | ||
@@ -689,16 +756,11 @@ matchingParams = {}; | ||
param = _ref[_i]; | ||
if ((jQuery.inArray(param.paramType, paramTypes) >= 0) && args[param.name]) { | ||
if (args && args[param.name]) { | ||
matchingParams[param.name] = args[param.name]; | ||
} | ||
} | ||
if (includeApiKey && (this.resource.api.api_key != null) && this.resource.api.api_key.length > 0) { | ||
matchingParams[this.resource.api.apiKeyName] = this.resource.api.api_key; | ||
_ref1 = this.resource.api.headers; | ||
for (name in _ref1) { | ||
value = _ref1[name]; | ||
matchingParams[name] = value; | ||
} | ||
if (jQuery.inArray('header', paramTypes) >= 0) { | ||
_ref1 = this.resource.api.headers; | ||
for (name in _ref1) { | ||
value = _ref1[name]; | ||
matchingParams[name] = value; | ||
} | ||
} | ||
return matchingParams; | ||
@@ -708,9 +770,13 @@ }; | ||
SwaggerOperation.prototype.help = function() { | ||
var parameter, _i, _len, _ref; | ||
var msg, parameter, _i, _len, _ref; | ||
msg = ""; | ||
_ref = this.parameters; | ||
for (_i = 0, _len = _ref.length; _i < _len; _i++) { | ||
parameter = _ref[_i]; | ||
console.log(" " + parameter.name + (parameter.required ? ' (required)' : '') + " - " + parameter.description); | ||
if (msg !== "") { | ||
msg += "\n"; | ||
} | ||
msg += "* " + parameter.name + (parameter.required ? ' (required)' : '') + " - " + parameter.description; | ||
} | ||
return this; | ||
return msg; | ||
}; | ||
@@ -724,12 +790,13 @@ | ||
function SwaggerRequest(type, url, headers, body, successCallback, errorCallback, operation) { | ||
var obj, | ||
function SwaggerRequest(type, url, params, opts, successCallback, errorCallback, operation, execution) { | ||
var body, e, fields, headers, key, myHeaders, obj, param, parent, possibleParams, requestContentType, responseContentType, urlEncoded, value, values, | ||
_this = this; | ||
this.type = type; | ||
this.url = url; | ||
this.headers = headers; | ||
this.body = body; | ||
this.params = params; | ||
this.opts = opts; | ||
this.successCallback = successCallback; | ||
this.errorCallback = errorCallback; | ||
this.operation = operation; | ||
this.execution = execution; | ||
if (this.type == null) { | ||
@@ -750,26 +817,124 @@ throw "SwaggerRequest type is required (get/post/put/delete)."; | ||
} | ||
if (this.operation.resource.api.verbose) { | ||
console.log(this.asCurl()); | ||
this.type = this.type.toUpperCase(); | ||
headers = params.headers; | ||
myHeaders = {}; | ||
body = params.body; | ||
parent = params["parent"]; | ||
requestContentType = "application/json"; | ||
if (body && (this.type === "POST" || this.type === "PUT" || this.type === "PATCH")) { | ||
if (this.opts.requestContentType) { | ||
requestContentType = this.opts.requestContentType; | ||
} | ||
} else { | ||
if (((function() { | ||
var _i, _len, _ref, _results; | ||
_ref = this.operation.parameters; | ||
_results = []; | ||
for (_i = 0, _len = _ref.length; _i < _len; _i++) { | ||
param = _ref[_i]; | ||
if (param.paramType === "form") { | ||
_results.push(param); | ||
} | ||
} | ||
return _results; | ||
}).call(this)).length > 0) { | ||
requestContentType = "application/x-www-form-urlencoded"; | ||
} else if (this.type !== "DELETE") { | ||
requestContentType = null; | ||
} | ||
} | ||
this.headers || (this.headers = {}); | ||
if (this.operation.resource.api.api_key != null) { | ||
this.headers[this.apiKeyName] = this.operation.resource.api.api_key; | ||
if (requestContentType && this.operation.consumes) { | ||
if (this.operation.consumes.indexOf(requestContentType) === -1) { | ||
console.log("server doesn't consume " + requestContentType + ", try " + JSON.stringify(this.operation.consumes)); | ||
if (this.requestContentType === null) { | ||
requestContentType = this.operation.consumes[0]; | ||
} | ||
} | ||
} | ||
if (this.headers.mock == null) { | ||
responseContentType = null; | ||
if (this.type === "POST" || this.type === "GET") { | ||
if (this.opts.responseContentType) { | ||
responseContentType = this.opts.responseContentType; | ||
} else { | ||
responseContentType = "application/json"; | ||
} | ||
} else { | ||
responseContentType = null; | ||
} | ||
if (responseContentType && this.operation.produces) { | ||
if (this.operation.produces.indexOf(responseContentType) === -1) { | ||
console.log("server can't produce " + responseContentType); | ||
} | ||
} | ||
if (requestContentType && requestContentType.indexOf("application/x-www-form-urlencoded") === 0) { | ||
fields = {}; | ||
possibleParams = (function() { | ||
var _i, _len, _ref, _results; | ||
_ref = this.operation.parameters; | ||
_results = []; | ||
for (_i = 0, _len = _ref.length; _i < _len; _i++) { | ||
param = _ref[_i]; | ||
if (param.paramType === "form") { | ||
_results.push(param); | ||
} | ||
} | ||
return _results; | ||
}).call(this); | ||
values = {}; | ||
for (key in possibleParams) { | ||
value = possibleParams[key]; | ||
if (this.params[value.name]) { | ||
values[value.name] = this.params[value.name]; | ||
} | ||
} | ||
urlEncoded = ""; | ||
for (key in values) { | ||
value = values[key]; | ||
if (urlEncoded !== "") { | ||
urlEncoded += "&"; | ||
} | ||
urlEncoded += encodeURIComponent(key) + '=' + encodeURIComponent(value); | ||
} | ||
body = urlEncoded; | ||
} | ||
if (requestContentType) { | ||
myHeaders["Content-Type"] = requestContentType; | ||
} | ||
if (responseContentType) { | ||
myHeaders["Accept"] = responseContentType; | ||
} | ||
if (!((headers != null) && (headers.mock != null))) { | ||
obj = { | ||
type: this.type, | ||
url: this.url, | ||
data: JSON.stringify(this.body), | ||
dataType: 'json', | ||
error: function(xhr, textStatus, error) { | ||
return _this.errorCallback(xhr, textStatus, error); | ||
}, | ||
success: function(data) { | ||
return _this.successCallback(data); | ||
method: this.type, | ||
headers: myHeaders, | ||
body: body, | ||
on: { | ||
error: function(response) { | ||
return _this.errorCallback(response, _this.opts.parent); | ||
}, | ||
redirect: function(response) { | ||
return _this.successCallback(response, _this.opts.parent); | ||
}, | ||
307: function(response) { | ||
return _this.successCallback(response, _this.opts.parent); | ||
}, | ||
response: function(response) { | ||
return _this.successCallback(response, _this.opts.parent); | ||
} | ||
} | ||
}; | ||
if (obj.type.toLowerCase() === "post" || obj.type.toLowerCase() === "put") { | ||
obj.contentType = "application/json"; | ||
e = {}; | ||
if (typeof window !== 'undefined') { | ||
e = window; | ||
} else { | ||
e = exports; | ||
} | ||
jQuery.ajax(obj); | ||
e.authorizations.apply(obj); | ||
if (opts.mock == null) { | ||
new SwaggerHttp().execute(obj); | ||
} else { | ||
console.log(obj); | ||
return obj; | ||
} | ||
} | ||
@@ -797,12 +962,120 @@ } | ||
window.SwaggerApi = SwaggerApi; | ||
SwaggerHttp = (function() { | ||
window.SwaggerResource = SwaggerResource; | ||
SwaggerHttp.prototype.Shred = null; | ||
window.SwaggerOperation = SwaggerOperation; | ||
SwaggerHttp.prototype.shred = null; | ||
window.SwaggerRequest = SwaggerRequest; | ||
SwaggerHttp.prototype.content = null; | ||
window.SwaggerModelProperty = SwaggerModelProperty; | ||
function SwaggerHttp() { | ||
var identity, toString, | ||
_this = this; | ||
if (typeof window !== 'undefined') { | ||
this.Shred = require("./shred"); | ||
} else { | ||
this.Shred = require("shred"); | ||
} | ||
this.shred = new this.Shred(); | ||
identity = function(x) { | ||
return x; | ||
}; | ||
toString = function(x) { | ||
return x.toString; | ||
}; | ||
if (typeof window !== 'undefined') { | ||
this.content = require("./shred/content"); | ||
this.content.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], { | ||
parser: identity, | ||
stringify: toString | ||
}); | ||
} else { | ||
this.Shred.registerProcessor(["application/json; charset=utf-8", "application/json", "json"], { | ||
parser: identity, | ||
stringify: toString | ||
}); | ||
} | ||
} | ||
SwaggerHttp.prototype.execute = function(obj) { | ||
return this.shred.request(obj); | ||
}; | ||
return SwaggerHttp; | ||
})(); | ||
SwaggerAuthorizations = (function() { | ||
SwaggerAuthorizations.prototype.authz = null; | ||
function SwaggerAuthorizations() { | ||
this.authz = {}; | ||
} | ||
SwaggerAuthorizations.prototype.add = function(name, auth) { | ||
this.authz[name] = auth; | ||
return auth; | ||
}; | ||
SwaggerAuthorizations.prototype.apply = function(obj) { | ||
var key, value, _ref, _results; | ||
_ref = this.authz; | ||
_results = []; | ||
for (key in _ref) { | ||
value = _ref[key]; | ||
_results.push(value.apply(obj)); | ||
} | ||
return _results; | ||
}; | ||
return SwaggerAuthorizations; | ||
})(); | ||
ApiKeyAuthorization = (function() { | ||
ApiKeyAuthorization.prototype.type = null; | ||
ApiKeyAuthorization.prototype.name = null; | ||
ApiKeyAuthorization.prototype.value = null; | ||
function ApiKeyAuthorization(name, value, type) { | ||
this.name = name; | ||
this.value = value; | ||
this.type = type; | ||
} | ||
ApiKeyAuthorization.prototype.apply = function(obj) { | ||
if (this.type === "query") { | ||
if (obj.url.indexOf('?') > 0) { | ||
obj.url = obj.url + "&" + this.name + "=" + this.value; | ||
} else { | ||
obj.url = obj.url + "?" + this.name + "=" + this.value; | ||
} | ||
return true; | ||
} else if (this.type === "header") { | ||
return obj.headers[this.name] = this.value; | ||
} | ||
}; | ||
return ApiKeyAuthorization; | ||
})(); | ||
this.SwaggerApi = SwaggerApi; | ||
this.SwaggerResource = SwaggerResource; | ||
this.SwaggerOperation = SwaggerOperation; | ||
this.SwaggerRequest = SwaggerRequest; | ||
this.SwaggerModelProperty = SwaggerModelProperty; | ||
this.ApiKeyAuthorization = ApiKeyAuthorization; | ||
this.authorizations = new SwaggerAuthorizations(); | ||
}).call(this); |
@@ -11,3 +11,3 @@ { | ||
"description": "swagger.js is a javascript client for use with swaggering APIs.", | ||
"version": "1.0.4", | ||
"version": "2.0.0-develop", | ||
"homepage": "http://swagger.wordnik.com", | ||
@@ -27,3 +27,5 @@ "repository": { | ||
}, | ||
"dependencies": {}, | ||
"dependencies": { | ||
"shred": "0.8.8" | ||
}, | ||
"devDependencies": { | ||
@@ -30,0 +32,0 @@ "coffee-script": "~1.5.0" |
185
README.md
This is the Wordnik Swagger javascript client for use with [swagger](http://swagger.wordnik.com) enabled APIs. | ||
It's written in CoffeeScript and tested with Jasmine. | ||
It's written in CoffeeScript and tested with Jasmine, and is the fastest way to enable a javascript client to communicate with a swagger-enabled server. | ||
@@ -11,146 +11,101 @@ Find out more about the swagger project at [swagger.wordnik.com](http://swagger.wordnik.com), | ||
### Usage | ||
### Calling an API with swagger + node.js! | ||
Point swagger.js at a resource discovery file like | ||
[api.wordnik.com/v4/resources.json](http://api.wordnik.com/v4/resources.json) | ||
and it builds itself at runtime. | ||
```html | ||
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> | ||
<script type="text/javascript" src="https://raw.github.com/wordnik/swagger.js/master/lib/swagger.js"></script> | ||
<script type="text/javascript"> | ||
$(function() { | ||
window.wordnik = new SwaggerApi({ | ||
discoveryUrl: "http://api.wordnik.com/v4/resources.json", | ||
apiKey: "MY_API_KEY", | ||
success: function() { | ||
console.log('Shall we dance?'); | ||
} | ||
}); | ||
}); | ||
</script> | ||
Install swagger-client: | ||
``` | ||
npm install swagger-client | ||
``` | ||
### How it Works | ||
Then let swagger do the work! | ||
```js | ||
var swagger = require("swagger-client") | ||
When initialized, the swagger.js client will build itself based on the (valid) swagger json files. You | ||
initialize the client like such: | ||
```javascript | ||
wordnik = new SwaggerApi({ | ||
discoveryUrl: "http://api.wordnik.com/v4/resources.json", | ||
api_key: 'YOUR_API_KEY', // Don't have a Wordnik API key? Get one at developer.wordnik.com | ||
verbose: true, | ||
success: function() { console.log("Your client is ready to swagger."); } | ||
var s = new swagger.SwaggerApi({ | ||
discoveryUrl: 'http://localhost:8002/api/api-docs' | ||
}); | ||
``` | ||
s.build(); | ||
After executing the above code you should see the success message in your console. | ||
s.apis.pet.getPetById({petId:1}); | ||
### Object Hierarchy | ||
``` | ||
Now you have access to an object called `wordnik`. | ||
This object is what swagger.js builds at runtime when you | ||
point it at a `discoveryUrl`. Try exploring it in the console: | ||
That's it! You'll get a JSON response with the default callback handler: | ||
```javascript | ||
wordnik | ||
wordnik.apis | ||
wordnik.apis.word.operations | ||
wordnik.apis.word.operations.getDefinition | ||
```json | ||
{ | ||
"id": 1, | ||
"category": { | ||
"id": 2, | ||
"name": "Cats" | ||
}, | ||
"name": "Cat 1", | ||
"photoUrls": [ | ||
"url1", | ||
"url2" | ||
], | ||
"tags": [ | ||
{ | ||
"id": 1, | ||
"name": "tag1" | ||
}, | ||
{ | ||
"id": 2, | ||
"name": "tag2" | ||
} | ||
], | ||
"status": "available" | ||
} | ||
``` | ||
### Quick Reference | ||
Need to pass an API key? Configure one as a querystring: | ||
You also get some console help() methods for quick reference. Some examples: | ||
```js | ||
swagger.authorizations.add("apiKey", new swagger.ApiKeyAuthorization("api_key","special-key","query")); | ||
``` | ||
```javascript | ||
// Apis | ||
wordnik.help() | ||
...or with a header: | ||
// Apis | ||
wordnik.resource.word.help() | ||
// Operations | ||
wordnik.apis.word.operations.getExamples.help() | ||
```js | ||
swagger.authorizations.add("apiKey", new swagger.ApiKeyAuthorization("api_key","special-key","header")); | ||
``` | ||
### Making Requests | ||
There are two ways to make a request: | ||
### Calling an API with swagger + the browser! | ||
```javascript | ||
// shorthand form | ||
wordnik.word.getDefinitions(args, callback); | ||
Download `swagger.js` and `shred.bundle.js` into your lib folder | ||
// longhand form | ||
wordnik.apis.word.operations.getDefinitions.do(args, callback); | ||
```js | ||
<script src='lib/shred.bundle.js' type='text/javascript'></script> | ||
<script src='lib/swagger.js' type='text/javascript'></script> | ||
<script type="text/javascript"> | ||
// initialize swagger, point to a resource listing | ||
window.swagger = new SwaggerApi({discoveryUrl: "http://petstore.swagger.wordnik.com/api/api-docs.json"}); | ||
swagger.build(); | ||
// example usage | ||
wordnik.word.getDefinitions({word: 'bliss'}, function(definitions) { | ||
console.log(definitions); | ||
}) | ||
``` | ||
// add a success handler to dump the raw json into a div element named `mydata` | ||
success = function(data) { | ||
document.getElementById("mydata").innerHTML = data.content.data; | ||
} | ||
### Request Headers | ||
You can include your own headers in the args object: | ||
```javascript | ||
args = {word: 'swole', limit:5} | ||
args.headers = {magic: 'potion'} | ||
callback = function(examples) { console.log(examples); } | ||
wordnik.word.getExamples(args, callback); | ||
// a function to fetch a pet | ||
function getPet() { | ||
swagger.apis.pet.getPetById({petId:1}, success); | ||
} | ||
</script> | ||
``` | ||
If you want to initialize the Request without actually firing | ||
off a network request you can set a header called `mock` with any value. | ||
### How does it work? | ||
The swagger javascript client reads the swagger api definition directly from the server. As it does, it constructs a client based on the api definition, which means it is completely dynamic. It even reads the api text descriptions (which are intended for humans!) and provides help if you need it: | ||
### Request Body | ||
For GETs and POSTs, you can include the request body in the args object: | ||
```javascript | ||
args = {} | ||
args.body = {name: "gizmo", description: "A thing that does stuff."} | ||
callback = function(thing) { console.log(thing); } | ||
myApi.things.createThing(args, callback); | ||
```js | ||
s.apis.pet.getPetById.help() | ||
'* petId (required) - ID of pet that needs to be fetched' | ||
``` | ||
### Debugging / cURL | ||
The HTTP requests themselves are handled by the excellent [shred](https://github.com/automatthew/shred) library, which has a ton of features itself. But it runs on both node and the browser. | ||
Set `verbose` to `true` when initializing your client to see cURL | ||
equivalents of your requests in the browser console, complete with headers: | ||
```javascript | ||
wordnik = new SwaggerApi({ | ||
api_key: 'YOUR_API_KEY', | ||
verbose: true, | ||
success: function() { | ||
args = { | ||
word: 'dog' | ||
headers: {fubar: 'maybe'} | ||
} | ||
wordnik.word.getDefinitions.do(args, function(definitions){ | ||
console.log(definitions[0].word); | ||
for (var i = 0; i < definitions.length; i++) { | ||
var definition = definitions[i]; | ||
console.log(definition.partOfSpeech + ": " + definition.text); | ||
} | ||
}); | ||
} | ||
}); | ||
// Console output: | ||
// curl --header "fubar: maybe" http://api.wordnik.com/v4/word.json/dog/definitions?api_key=YOUR_API_KEY | ||
// dog | ||
// noun: A domesticated carnivorous mammal (Canis familiaris) related to the foxes and wolves and raised in a wide variety of breeds. | ||
// noun: Any of various carnivorous mammals of the family Canidae, such as the dingo. | ||
// noun: A male animal of the family Canidae, especially of the fox or a domesticated breed. | ||
// etc... | ||
``` | ||
Development | ||
----------- | ||
Please [fork the code](https://github.com/wordnik/swagger.js) and help us improve | ||
Please [fork the code](https://github.com/wordnik/swagger-js) and help us improve | ||
swagger.js. Send us a pull request and **we'll mail you a wordnik T-shirt!** | ||
@@ -157,0 +112,0 @@ |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Network access
Supply chain riskThis module accesses the network.
Found 3 instances in 1 package
Debug access
Supply chain riskUses debug, reflection and dynamic code execution features.
Found 1 instance in 1 package
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Deprecated
MaintenanceThe maintainer of the package marked it as deprecated. This could indicate that a single version should not be used, or that the package is no longer maintained and any new vulnerabilities will not be fixed.
Found 1 instance in 1 package
414353
28
7321
0
1
2
148
10
7
+ Addedshred@0.8.8
+ Addedax@0.1.8(transitive)
+ Addedcookiejar@1.3.2(transitive)
+ Addediconv-lite@0.6.3(transitive)
+ Addedsafer-buffer@2.1.2(transitive)
+ Addedshred@0.8.8(transitive)
+ Addedsprintf@0.1.1(transitive)