updated with npm-managed swagger package

This commit is contained in:
Tony Tam 2013-01-04 11:07:12 -08:00
parent 7370354535
commit 5d60632aa6
9 changed files with 63 additions and 934 deletions

View File

@ -1,56 +0,0 @@
function createEnum(input) {
if (input && input.toString().indexOf(",") > 0) {
var output = [];
var array = input.split(",");
array.forEach(function(item) {
output.push(item);
})
return output;
}
}
exports.query = exports.q = function(name, description, dataType, required, allowMultiple, allowableValues, defaultValue) {
return {
"name" : name,
"description" : description,
"dataType" : dataType,
"required" : required,
"allowMultiple" : allowMultiple,
"allowableValues" : createEnum(allowableValues),
"defaultValue" : defaultValue,
"paramType" : "query"
};
};
exports.path = function(name, description, dataType, allowableValues) {
return {
"name" : name,
"description" : description,
"dataType" : dataType = "string",
"required" : true,
"allowMultiple" : false,
"allowableValues" : createEnum(allowableValues),
"paramType" : "path"
};
};
exports.post = function(dataType, description) {
return {
"description" : description,
"dataType" : dataType,
"required" : true,
"paramType" : "body"
};
};
exports.header = function(name, description, dataType, required) {
return {
"name" : name,
"description" : description,
"dataType" : dataType,
"required" : true,
"allowMultiple" : false,
"allowableValues" : createEnum(allowableValues),
"paramType" : "header"
};
};

View File

@ -1,68 +0,0 @@
var Randomizer = {
'intBetween': function(a, b) {
return Math.floor(Math.random()*(b-a+1)+a);
},
'string': function() {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 24;
var randomstring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
return randomstring;
},
'int': function() {
return this.intBetween(0, 10000);
},
'long': function() {
return this.int();
},
'double': function() {
return Math.random()*1000000;
},
'boolean': function() {
return this.intBetween(1,2) == 1;
},
'__date': function() {
var m = this.intBetween(1, 12);
if (m < 10) { m = '0'+m; }
var d = this.intBetween(1, 28);
if (d < 10) { d = '0'+d; }
return this.intBetween(1800, 2015) + '-' + m + '-' + d;
},
'date': function() {
return this.__date() + 'T' + this.__time();
},
'__time': function() {
var h = this.intBetween(0, 23);
if (h < 10) { h = '0'+h; }
var m = this.intBetween(0, 59);
if (m < 10) { m = '0'+m; }
var s = this.intBetween(0, 59);
if (s < 10) { s = '0'+s; }
return h + ':' + m + ':' + s + '+01:00';
},
'array': function(type, length) {
var out = new Array();
if (!length) {
length = this.intBetween(1, 5); }
for (var i = 0; i < length; i++) {
out.push(this[type]()); }
return out;
}
};
exports.intBetween = Randomizer.intBetween;
exports.string = Randomizer.string;
exports.int = Randomizer.int;
exports.long = Randomizer.long;
exports.double = Randomizer.double;
exports.boolean = Randomizer.boolean;
exports.array = Randomizer.array;
exports.__date = Randomizer.__date;
exports.date = Randomizer.date;
exports.__time = Randomizer.__time;

View File

@ -1,612 +0,0 @@
var resourcePath = "/resources.json";
var basePath = "/";
var swaggerVersion = "1.1";
var apiVersion = "0.0";
var resources = {};
var validators = [];
var appHandler = null;
var allowedMethods = ['get', 'post', 'put', 'delete'];
var allowedDataTypes = ['string', 'int', 'long', 'double', 'boolean', 'date', 'array'];
var Randomizer = require(__dirname + '/randomizer.js');
var params = require(__dirname + '/paramTypes.js');
var allModels = {};
/**
* Initialize Randomizer Caching
*/
var RandomStorage = {};
for (var i = 0; i < allowedDataTypes.length; i++) {
RandomStorage[allowedDataTypes[i]] = {}; }
/**
* sets the base path, api version
*
* @param app
* @param bp
* @param av
*/
function configure(bp, av) {
basePath = bp;
apiVersion = av;
setResourceListingPaths(appHandler);
appHandler.get(resourcePath, resourceListing);
// update resources if already configured
for(key in resources) {
var r = resources[key];
r.apiVersion = av;
r.basePath = bp;
}
}
/**
* creates declarations for each resource
*
* @param app
*/
function setResourceListingPaths(app) {
for (var key in resources) {
app.get("/" + key.replace("\.\{format\}", ".json"), function(req, res) {
var r = resources[req.url.substr(1).split('?')[0].replace('.json', '.{format}')];
if (!r) {
return stopWithError(res, {'description': 'internal error', 'code': 500}); }
else {
res.header('Access-Control-Allow-Origin', "*");
res.header("Content-Type", "application/json; charset=utf-8");
var key = req.url.substr(1).replace('.json', '.{format}').split('?')[0];
var data = applyFilter(req, res, resources[key]);
data.basePath = basePath;
if (data.code) {
res.send(data, data.code); }
else {
res.header('Access-Control-Allow-Origin', "*");
res.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
res.header("Access-Control-Allow-Headers", "Content-Type");
res.header("Content-Type", "application/json; charset=utf-8");
res.send(JSON.stringify(applyFilter(req, res, r)));
}
}
});
}
}
/**
* generate random date for type
*
* @param type type of data (must be defined in allowedDataTypes)
* @param withRandom fill with random data
* @return value
*/
function randomDataByType(type, withRandom, subType) {
type = type.toLowerCase();
if (allowedDataTypes.indexOf(type)<0) {
return null; }
return Randomizer[type](subType);
}
/**
* Get cache for type and identifier
* @param type
* @param id
* @param key
* @return value
*/
function getCache(type, id, key) {
if (id && id != -1 && RandomStorage[type] && RandomStorage[type][key+id]) {
return RandomStorage[type][key + id]; }
else {
return null; }
}
/**
* Set cache for type and identifier
* @param type
* @param id
* @param key
* @param value
*/
function setCache(curType, id, key, value) {
if (id && id != -1 && RandomStorage[curType]) {
RandomStorage[curType][key + id] = value; }
}
/**
* try to generate object from model defintion
* @param model
* @param withData fill model with data
* @param withRandom generate random values
* @return object
*/
function containerByModel(model, withData, withRandom) {
var item = {};
for (key in model.properties) {
var curType = model.properties[key].type.toLowerCase();
var value = '';
if (withData && withData[key]) {
value = withData[key]; }
if (value == '' && withRandom) {
var cache = getCache(curType, withRandom, key);
if (cache) {
value = cache; }
else {
if (model.properties[key].enum) {
value = model.properties[key].enum[Randomizer.intBetween(0, model.properties[key].enum.length-1)]; }
else {
var subType = false;
if (model.properties[key].items && model.properties[key].items.type) {
subType = model.properties[key].items.type; }
var curKey = key;
value = randomDataByType(curType, withRandom, subType);
var key = curKey;
}
}
setCache(curType, withRandom, key, value);
}
if (value == '' && curType == 'Array') {
value = []; }
item[key] = value;
}
return item;
}
/**
* filters resource listing by access
*
* @param req
* @param res
* @param r
* @returns
*/
function applyFilter(req, res, r) {
var route = req.route;
var excludedPaths = [];
if (!r || !r.apis) {
return stopWithError(res, {'description': 'internal error', 'code': 500}); }
for (var key in r.apis) {
var api = r.apis[key];
for (var opKey in api.operations) {
var op = api.operations[opKey];
var path = api.path.replace(/{.*\}/, "*");
if (!canAccessResource(req, route + path, op.httpMethod)) {
excludedPaths.push(op.httpMethod + ":" + api.path); }
}
}
// clone attributes if any
var output = shallowClone(r);
// clone models
var requiredModels = [];
// clone methods that have access
output.apis = new Array();
var apis = JSON.parse(JSON.stringify(r.apis));
for (var i in apis) {
var api = apis[i];
var clonedApi = shallowClone(api);
clonedApi.operations = new Array();
var shouldAdd = true;
for (var o in api.operations){
var operation = api.operations[o];
if (excludedPaths.indexOf(operation.httpMethod + ":" + api.path)>=0) {
break; }
else {
clonedApi.operations.push(JSON.parse(JSON.stringify(operation)));
addModelsFromResponse(operation, requiredModels);
}
}
if (clonedApi.operations.length > 0) {
// only add cloned api if there are operations
output.apis.push(clonedApi);
}
}
// add models to output
output.models = {};
for (var i in requiredModels){
var modelName = requiredModels[i];
var model = allModels.models[modelName];
if(model){
output.models[requiredModels[i]] = model;
}
}
// look in object graph
for (key in output.models) {
var model = output.models[key];
if (model && model.properties) {
for (var key in model.properties) {
var t = model.properties[key].type;
switch (t){
case "Array":
if (model.properties[key].items) {
var ref = model.properties[key].items.$ref;
if (ref && requiredModels.indexOf(ref) < 0) {
requiredModels.push(ref);
}
}
break;
case "string":
case "long":
break;
default:
if (requiredModels.indexOf(t) < 0) {
requiredModels.push(t);
}
break;
}
}
}
}
for (var i in requiredModels){
var modelName = requiredModels[i];
if(!output[modelName]) {
var model = allModels.models[modelName];
if(model){
output.models[requiredModels[i]] = model;
}
}
}
return output;
}
/**
* Add model to list and parse List[model] elements
* @param operation
* @param models
*/
function addModelsFromResponse(operation, models){
var responseModel = operation.responseClass;
if (responseModel) {
responseModel = responseModel.replace(/^List\[/,"").replace(/\]/,"");
if (models.indexOf(responseModel) < 0) {
models.push(responseModel);
}
}
}
function shallowClone(obj) {
var cloned = new Object();
for (var i in obj) {
if (typeof (obj[i]) != "object") {
cloned[i] = obj[i]; }
}
return cloned;
}
/**
* function for filtering a resource. override this with your own implementation
*
* @param req
* @param path
* @param httpMethod
* @returns {Boolean}
*/
function canAccessResource(req, path, httpMethod) {
for (var i in validators) {
if (!validators[i](req,path,httpMethod)) {
return false; }
}
return true;
}
/**
* returns the json representation of a resource
*
* @param request
* @param response
*/
function resourceListing(request, response) {
var r = {"apiVersion" : apiVersion, "swaggerVersion": swaggerVersion, "basePath": basePath, "apis": []};
for (var key in resources) {
r.apis.push({"path": "/" + key, "description": "none"});
}
writeHeaders(response);
response.write(JSON.stringify(r));
response.end();
}
/**
* adds a method to the api along with a spec. If the spec fails to validate, it won't be added
*
* @param app
* @param callback
* @param spec
*/
function addMethod(app, callback, spec) {
var rootPath = spec.path.split("/")[1];
var root = resources[rootPath];
if (root && root.apis) {
for (var key in root.apis) {
var api = root.apis[key];
if (api && api.path == spec.path && api.method == spec.method) {
// found matching path and method, add & return
appendToApi(root, api, spec);
return;
}
}
}
var api = {"path" : spec.path};
if (!resources[rootPath]) {
if (!root) {
var resourcePath = "/" + rootPath.replace("\.\{format\}", "");
root = {
"apiVersion" : apiVersion, "swaggerVersion": swaggerVersion, "basePath": basePath, "resourcePath": resourcePath, "apis": [], "models" : []
};
}
resources[rootPath] = root;
}
root.apis.push(api);
appendToApi(root, api, spec);
// TODO: add some XML support
// convert .{format} to .json, make path params happy
var fullPath = spec.path.replace("\.\{format\}", ".json").replace(/\/{/g, "/:").replace(/\}/g,"");
var currentMethod = spec.method.toLowerCase();
if (allowedMethods.indexOf(currentMethod)>-1) {
app[currentMethod](fullPath, function(req,res) {
writeHeaders(res);
if (!canAccessResource(req, req.url.substr(1).split('?')[0].replace('.json', '.*'), req.method)) {
res.send(JSON.stringify({"description":"forbidden", "code":403}), 403);
} else {
try {
callback(req,res); }
catch (ex) {
if (ex.code && ex.description) {
res.send(JSON.stringify(ex), ex.code); }
else {
console.error(spec.method + " failed for path '" + require('url').parse(req.url).href + "': " + ex);
res.send(JSON.stringify({"description":"unknown error","code":500}), 500);
}
}
}
});
} else {
console.log('unable to add ' + currentMethod.toUpperCase() + ' handler');
return;
}
}
/**
* Set expressjs app handler
* @param app
*/
function setAppHandler(app) {
appHandler = app;
}
/**
* Add swagger handlers to express
* @param type http method
* @param handlers list of handlers to be added
*/
function addHandlers(type, handlers) {
for (var i = 0; i < handlers.length; i++) {
var handler = handlers[i];
handler.spec.method = type;
addMethod(appHandler, handler.action, handler.spec);
}
}
/**
* Discover swagger handler from resource
*/
function discover(resource) {
for (var key in resource) {
if (resource[key].spec && resource[key].spec.method && allowedMethods.indexOf(resource[key].spec.method.toLowerCase())>-1) {
addMethod(appHandler, resource[key].action, resource[key].spec); }
else {
console.log('auto discover failed for: ' + key); }
}
}
/**
* Discover swagger handler from resource file path
*/
function discoverFile(file) {
return discover(require(file));
}
function addGet() {
addHandlers('GET', arguments);
return this;
}
function addPost() {
addHandlers('POST', arguments);
return this;
}
function addDelete() {
addHandlers('DELETE', arguments);
return this;
}
function addPut() {
addHandlers('PUT', arguments);
return this;
}
function addModels(models) {
allModels = models;
return this;
}
function wrap(callback, req, resp){
callback(req,resp);
}
function writeHeaders(response) {
response.header('Access-Control-Allow-Origin', "*");
response.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
response.header("Access-Control-Allow-Headers", "Content-Type");
response.header("Content-Type", "application/json; charset=utf-8");
}
function appendToApi(rootResource, api, spec) {
if (!api.description) {
api.description = spec.description;
}
var validationErrors = [];
if(!spec.nickname || spec.nickname.indexOf(" ")>=0){
// nicknames don't allow spaces
validationErrors.push({"path": api.path, "error": "invalid nickname '" + spec.nickname + "'"});
}
// validate params
for ( var paramKey in spec.params) {
var param = spec.params[paramKey];
if(param.allowableValues) {
var avs = param.allowableValues.toString();
var type = avs.split('[')[0];
if(type == 'LIST'){
var values = avs.match(/\[(.*)\]/g).toString().replace('\[','').replace('\]', '').split(',');
param.allowableValues = {valueType: type, values: values};
}
else if (type == 'RANGE') {
var values = avs.match(/\[(.*)\]/g).toString().replace('\[','').replace('\]', '').split(',');
param.allowableValues = {valueType: type, min: values[0], max: values[1]};
}
}
switch (param.paramType) {
case "path":
if (api.path.indexOf("{" + param.name + "}") < 0) {
validationErrors.push({"path": api.path, "name": param.name, "error": "invalid path"}); }
break;
case "query":
break;
case "body":
break;
default:
validationErrors.push({"path": api.path, "name": param.name, "error": "invalid param type " + param.paramType});
break;
}
}
if (validationErrors.length > 0) {
console.log(validationErrors);
return;
}
if (!api.operations) {
api.operations = []; }
// TODO: replace if existing HTTP operation in same api path
var op = {
"parameters" : spec.params,
"httpMethod" : spec.method,
"notes" : spec.notes,
"errorResponses" : spec.errorResponses,
"nickname" : spec.nickname,
"summary" : spec.summary
};
if (spec.responseClass) {
op.responseClass = spec.responseClass;
}
else {
op.responseClass = "void";
}
api.operations.push(op);
if (!rootResource.models) {
rootResource.models = {};
}
}
function addValidator(v) {
validators.push(v);
}
/**
* Create Error JSON by code and text
* @param int code
* @param string description
* @return obj
*/
function error(code, description) {
return {"code" : code, "description" : description};
}
/**
* Stop express ressource with error code
* @param obj res expresso response
* @param obj error error object with code and description
*/
function stopWithError(res, error) {
res.header('Access-Control-Allow-Origin', "*");
res.header("Content-Type", "application/json; charset=utf-8");
if (error && error.description && error.code) {
res.send(JSON.stringify(error), error.code); }
else {
res.send(JSON.stringify({'description': 'internal error', 'code': 500}), 500); }
};
/**
* Export most needed error types for easier handling
*/
exports.errors = {
'notFound': function(field, res) {
if (!res) {
return {"code": 404, "description": field + ' not found'}; }
else {
res.send({"code": 404, "description": field + ' not found'}, 404); }
},
'invalid': function(field, res) {
if (!res) {
return {"code": 400, "description": 'invalid ' + field}; }
else {
res.send({"code": 400, "description": 'invalid ' + field}, 404); }
},
'forbidden': function(res) {
if (!res) {
return {"code": 403, "description": 'forbidden' }; }
else {
res.send({"code": 403, "description": 'forbidden'}, 403); }
}
};
exports.params = params;
exports.queryParam = exports.params.query;
exports.pathParam = exports.params.path;
exports.postParam = exports.params.post;
exports.getModels = allModels;
exports.error = error;
exports.stopWithError = stopWithError;
exports.stop = stopWithError;
exports.addValidator = addValidator;
exports.configure = configure;
exports.canAccessResource = canAccessResource;
exports.resourcePath = resourcePath;
exports.resourceListing = resourceListing;
exports.addGet = addGet;
exports.addPost = addPost;
exports.addPut = addPut;
exports.addDelete = addDelete;
exports.addGET = addGet;
exports.addPOST = addPost;
exports.addPUT = addPut;
exports.addDELETE = addDelete;
exports.addModels = addModels;
exports.setAppHandler = setAppHandler;
exports.discover = discover;
exports.discoverFile = discoverFile;
exports.containerByModel = containerByModel;
exports.Randomizer = Randomizer;

View File

@ -1,7 +1,6 @@
var sw = require("../Common/node/swagger.js"); var swagger = require("swagger-node-express");
var param = require("../Common/node/paramTypes.js");
var url = require("url"); var url = require("url");
var swe = sw.errors; var errors = swagger.errors;
/* add model includes */ /* add model includes */
@ -22,14 +21,14 @@ exports.getPetById = {
"notes" : "Returns a pet based on ID", "notes" : "Returns a pet based on ID",
"summary" : "Find pet by ID", "summary" : "Find pet by ID",
"method": "GET", "method": "GET",
"params" : [].concat([param.path("petId", "ID of pet that needs to be fetched")]).concat([]).concat([]), "params" : [].concat([swagger.pathParam("petId", "ID of pet that needs to be fetched")]).concat([]).concat([]),
"responseClass" : "Pet", "responseClass" : "Pet",
"errorResponses" : [swe.invalid('id'), swe.notFound('Pet')], "errorResponses" : [errors.invalid('id'), errors.notFound('Pet')],
"nickname" : "getPetById" "nickname" : "getPetById"
}, },
'action': function (req,res) { 'action': function (req,res) {
if (!req.params.petId) { if (!req.params.petId) {
throw swe.invalid('petId'); throw errors.invalid('petId');
} }
writeResponse(res, {message: "how about implementing getPetById as a GET method?"}); writeResponse(res, {message: "how about implementing getPetById as a GET method?"});
} }
@ -41,15 +40,15 @@ exports.addPet = {
"notes" : "", "notes" : "",
"summary" : "Add a new pet to the store", "summary" : "Add a new pet to the store",
"method": "POST", "method": "POST",
"params" : [].concat([]).concat([]).concat([param.post("Pet", "Pet object that needs to be added to the store", true) "params" : [].concat([]).concat([]).concat([swagger.postParam("Pet", "Pet object that needs to be added to the store", true)
]), ]),
"responseClass" : "", "responseClass" : "",
"errorResponses" : [swe.invalid('id'), swe.notFound('')], "errorResponses" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "addPet" "nickname" : "addPet"
}, },
'action': function (req,res) { 'action': function (req,res) {
if (!req.params.body) { if (!req.params.body) {
throw swe.invalid('body'); throw errors.invalid('body');
} }
writeResponse(res, {message: "how about implementing addPet as a POST method?"}); writeResponse(res, {message: "how about implementing addPet as a POST method?"});
} }
@ -61,15 +60,15 @@ exports.updatePet = {
"notes" : "", "notes" : "",
"summary" : "Update an existing pet", "summary" : "Update an existing pet",
"method": "PUT", "method": "PUT",
"params" : [].concat([]).concat([]).concat([param.post("Pet", "Pet object that needs to be updated in the store", true) "params" : [].concat([]).concat([]).concat([swagger.postParam("Pet", "Pet object that needs to be updated in the store", true)
]), ]),
"responseClass" : "", "responseClass" : "",
"errorResponses" : [swe.invalid('id'), swe.notFound('')], "errorResponses" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "updatePet" "nickname" : "updatePet"
}, },
'action': function (req,res) { 'action': function (req,res) {
if (!req.params.body) { if (!req.params.body) {
throw swe.invalid('body'); throw errors.invalid('body');
} }
writeResponse(res, {message: "how about implementing updatePet as a PUT method?"}); writeResponse(res, {message: "how about implementing updatePet as a PUT method?"});
} }
@ -81,14 +80,14 @@ exports.findPetsByStatus = {
"notes" : "Multiple status values can be provided with comma seperated strings", "notes" : "Multiple status values can be provided with comma seperated strings",
"summary" : "Finds Pets by status", "summary" : "Finds Pets by status",
"method": "GET", "method": "GET",
"params" : [param.query("status", "Status values that need to be considered for filter", "string", true, true, "LIST[available,pending,sold]", "available")].concat([]).concat([]).concat([]), "params" : [swagger.queryParam("status", "Status values that need to be considered for filter", "string", true, true, "", "available")].concat([]).concat([]).concat([]),
"responseClass" : "List[Pet]", "responseClass" : "List[Pet]",
"errorResponses" : [swe.invalid('id'), swe.notFound('List[Pet]')], "errorResponses" : [errors.invalid('id'), errors.notFound('List[Pet]')],
"nickname" : "findPetsByStatus" "nickname" : "findPetsByStatus"
}, },
'action': function (req,res) { 'action': function (req,res) {
if (!req.params.status) { if (!req.params.status) {
throw swe.invalid('status'); throw errors.invalid('status');
} }
writeResponse(res, {message: "how about implementing findPetsByStatus as a GET method?"}); writeResponse(res, {message: "how about implementing findPetsByStatus as a GET method?"});
} }
@ -100,14 +99,14 @@ exports.findPetsByTags = {
"notes" : "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", "notes" : "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.",
"summary" : "Finds Pets by tags", "summary" : "Finds Pets by tags",
"method": "GET", "method": "GET",
"params" : [param.query("tags", "Tags to filter by", "string", true, true, "")].concat([]).concat([]).concat([]), "params" : [swagger.queryParam("tags", "Tags to filter by", "string", true, true, "")].concat([]).concat([]).concat([]),
"responseClass" : "List[Pet]", "responseClass" : "List[Pet]",
"errorResponses" : [swe.invalid('id'), swe.notFound('List[Pet]')], "errorResponses" : [errors.invalid('id'), errors.notFound('List[Pet]')],
"nickname" : "findPetsByTags" "nickname" : "findPetsByTags"
}, },
'action': function (req,res) { 'action': function (req,res) {
if (!req.params.tags) { if (!req.params.tags) {
throw swe.invalid('tags'); throw errors.invalid('tags');
} }
writeResponse(res, {message: "how about implementing findPetsByTags as a GET method?"}); writeResponse(res, {message: "how about implementing findPetsByTags as a GET method?"});
} }

View File

@ -1,7 +1,6 @@
var sw = require("../Common/node/swagger.js"); var swagger = require("swagger-node-express");
var param = require("../Common/node/paramTypes.js");
var url = require("url"); var url = require("url");
var swe = sw.errors; var errors = swagger.errors;
/* add model includes */ /* add model includes */
@ -22,14 +21,14 @@ exports.getOrderById = {
"notes" : "For valid response try integer IDs with value <= 5. Anything above 5 or nonintegers will generate API errors", "notes" : "For valid response try integer IDs with value <= 5. Anything above 5 or nonintegers will generate API errors",
"summary" : "Find purchase order by ID", "summary" : "Find purchase order by ID",
"method": "GET", "method": "GET",
"params" : [].concat([param.path("orderId", "ID of pet that needs to be fetched")]).concat([]).concat([]), "params" : [].concat([swagger.pathParam("orderId", "ID of pet that needs to be fetched")]).concat([]).concat([]),
"responseClass" : "Order", "responseClass" : "Order",
"errorResponses" : [swe.invalid('id'), swe.notFound('Order')], "errorResponses" : [errors.invalid('id'), errors.notFound('Order')],
"nickname" : "getOrderById" "nickname" : "getOrderById"
}, },
'action': function (req,res) { 'action': function (req,res) {
if (!req.params.orderId) { if (!req.params.orderId) {
throw swe.invalid('orderId'); throw errors.invalid('orderId');
} }
writeResponse(res, {message: "how about implementing getOrderById as a GET method?"}); writeResponse(res, {message: "how about implementing getOrderById as a GET method?"});
} }
@ -41,14 +40,14 @@ exports.deleteOrder = {
"notes" : "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", "notes" : "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors",
"summary" : "Delete purchase order by ID", "summary" : "Delete purchase order by ID",
"method": "DELETE", "method": "DELETE",
"params" : [].concat([param.path("orderId", "ID of the order that needs to be deleted")]).concat([]).concat([]), "params" : [].concat([swagger.pathParam("orderId", "ID of the order that needs to be deleted")]).concat([]).concat([]),
"responseClass" : "", "responseClass" : "",
"errorResponses" : [swe.invalid('id'), swe.notFound('')], "errorResponses" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "deleteOrder" "nickname" : "deleteOrder"
}, },
'action': function (req,res) { 'action': function (req,res) {
if (!req.params.orderId) { if (!req.params.orderId) {
throw swe.invalid('orderId'); throw errors.invalid('orderId');
} }
writeResponse(res, {message: "how about implementing deleteOrder as a DELETE method?"}); writeResponse(res, {message: "how about implementing deleteOrder as a DELETE method?"});
} }
@ -60,15 +59,15 @@ exports.placeOrder = {
"notes" : "", "notes" : "",
"summary" : "Place an order for a pet", "summary" : "Place an order for a pet",
"method": "POST", "method": "POST",
"params" : [].concat([]).concat([]).concat([param.post("Order", "order placed for purchasing the pet", true) "params" : [].concat([]).concat([]).concat([swagger.postParam("Order", "order placed for purchasing the pet", true)
]), ]),
"responseClass" : "", "responseClass" : "",
"errorResponses" : [swe.invalid('id'), swe.notFound('')], "errorResponses" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "placeOrder" "nickname" : "placeOrder"
}, },
'action': function (req,res) { 'action': function (req,res) {
if (!req.params.body) { if (!req.params.body) {
throw swe.invalid('body'); throw errors.invalid('body');
} }
writeResponse(res, {message: "how about implementing placeOrder as a POST method?"}); writeResponse(res, {message: "how about implementing placeOrder as a POST method?"});
} }

View File

@ -1,7 +1,6 @@
var sw = require("../Common/node/swagger.js"); var swagger = require("swagger-node-express");
var param = require("../Common/node/paramTypes.js");
var url = require("url"); var url = require("url");
var swe = sw.errors; var errors = swagger.errors;
/* add model includes */ /* add model includes */
@ -22,15 +21,15 @@ exports.createUsersWithArrayInput = {
"notes" : "", "notes" : "",
"summary" : "Creates list of users with given input array", "summary" : "Creates list of users with given input array",
"method": "POST", "method": "POST",
"params" : [].concat([]).concat([]).concat([param.post("Array[User]", "List of user object", true) "params" : [].concat([]).concat([]).concat([swagger.postParam("Array[User]", "List of user object", true)
]), ]),
"responseClass" : "", "responseClass" : "",
"errorResponses" : [swe.invalid('id'), swe.notFound('')], "errorResponses" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "createUsersWithArrayInput" "nickname" : "createUsersWithArrayInput"
}, },
'action': function (req,res) { 'action': function (req,res) {
if (!req.params.body) { if (!req.params.body) {
throw swe.invalid('body'); throw errors.invalid('body');
} }
writeResponse(res, {message: "how about implementing createUsersWithArrayInput as a POST method?"}); writeResponse(res, {message: "how about implementing createUsersWithArrayInput as a POST method?"});
} }
@ -42,15 +41,15 @@ exports.createUser = {
"notes" : "This can only be done by the logged in user.", "notes" : "This can only be done by the logged in user.",
"summary" : "Create user", "summary" : "Create user",
"method": "POST", "method": "POST",
"params" : [].concat([]).concat([]).concat([param.post("User", "Created user object", true) "params" : [].concat([]).concat([]).concat([swagger.postParam("User", "Created user object", true)
]), ]),
"responseClass" : "", "responseClass" : "",
"errorResponses" : [swe.invalid('id'), swe.notFound('')], "errorResponses" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "createUser" "nickname" : "createUser"
}, },
'action': function (req,res) { 'action': function (req,res) {
if (!req.params.body) { if (!req.params.body) {
throw swe.invalid('body'); throw errors.invalid('body');
} }
writeResponse(res, {message: "how about implementing createUser as a POST method?"}); writeResponse(res, {message: "how about implementing createUser as a POST method?"});
} }
@ -62,15 +61,15 @@ exports.createUsersWithListInput = {
"notes" : "", "notes" : "",
"summary" : "Creates list of users with given list input", "summary" : "Creates list of users with given list input",
"method": "POST", "method": "POST",
"params" : [].concat([]).concat([]).concat([param.post("List[User]", "List of user object", true) "params" : [].concat([]).concat([]).concat([swagger.postParam("List[User]", "List of user object", true)
]), ]),
"responseClass" : "", "responseClass" : "",
"errorResponses" : [swe.invalid('id'), swe.notFound('')], "errorResponses" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "createUsersWithListInput" "nickname" : "createUsersWithListInput"
}, },
'action': function (req,res) { 'action': function (req,res) {
if (!req.params.body) { if (!req.params.body) {
throw swe.invalid('body'); throw errors.invalid('body');
} }
writeResponse(res, {message: "how about implementing createUsersWithListInput as a POST method?"}); writeResponse(res, {message: "how about implementing createUsersWithListInput as a POST method?"});
} }
@ -82,18 +81,18 @@ exports.updateUser = {
"notes" : "This can only be done by the logged in user.", "notes" : "This can only be done by the logged in user.",
"summary" : "Updated user", "summary" : "Updated user",
"method": "PUT", "method": "PUT",
"params" : [].concat([param.path("username", "name that need to be deleted")]).concat([]).concat([param.post("User", "Updated user object", true) "params" : [].concat([swagger.pathParam("username", "name that need to be deleted")]).concat([]).concat([swagger.postParam("User", "Updated user object", true)
]), ]),
"responseClass" : "", "responseClass" : "",
"errorResponses" : [swe.invalid('id'), swe.notFound('')], "errorResponses" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "updateUser" "nickname" : "updateUser"
}, },
'action': function (req,res) { 'action': function (req,res) {
if (!req.params.username) { if (!req.params.username) {
throw swe.invalid('username'); throw errors.invalid('username');
} }
if (!req.params.body) { if (!req.params.body) {
throw swe.invalid('body'); throw errors.invalid('body');
} }
writeResponse(res, {message: "how about implementing updateUser as a PUT method?"}); writeResponse(res, {message: "how about implementing updateUser as a PUT method?"});
} }
@ -105,14 +104,14 @@ exports.deleteUser = {
"notes" : "This can only be done by the logged in user.", "notes" : "This can only be done by the logged in user.",
"summary" : "Delete user", "summary" : "Delete user",
"method": "DELETE", "method": "DELETE",
"params" : [].concat([param.path("username", "The name that needs to be deleted")]).concat([]).concat([]), "params" : [].concat([swagger.pathParam("username", "The name that needs to be deleted")]).concat([]).concat([]),
"responseClass" : "", "responseClass" : "",
"errorResponses" : [swe.invalid('id'), swe.notFound('')], "errorResponses" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "deleteUser" "nickname" : "deleteUser"
}, },
'action': function (req,res) { 'action': function (req,res) {
if (!req.params.username) { if (!req.params.username) {
throw swe.invalid('username'); throw errors.invalid('username');
} }
writeResponse(res, {message: "how about implementing deleteUser as a DELETE method?"}); writeResponse(res, {message: "how about implementing deleteUser as a DELETE method?"});
} }
@ -124,14 +123,14 @@ exports.getUserByName = {
"notes" : "", "notes" : "",
"summary" : "Get user by user name", "summary" : "Get user by user name",
"method": "GET", "method": "GET",
"params" : [].concat([param.path("username", "The name that needs to be fetched. Use user1 for testing.")]).concat([]).concat([]), "params" : [].concat([swagger.pathParam("username", "The name that needs to be fetched. Use user1 for testing.")]).concat([]).concat([]),
"responseClass" : "User", "responseClass" : "User",
"errorResponses" : [swe.invalid('id'), swe.notFound('User')], "errorResponses" : [errors.invalid('id'), errors.notFound('User')],
"nickname" : "getUserByName" "nickname" : "getUserByName"
}, },
'action': function (req,res) { 'action': function (req,res) {
if (!req.params.username) { if (!req.params.username) {
throw swe.invalid('username'); throw errors.invalid('username');
} }
writeResponse(res, {message: "how about implementing getUserByName as a GET method?"}); writeResponse(res, {message: "how about implementing getUserByName as a GET method?"});
} }
@ -143,17 +142,17 @@ exports.loginUser = {
"notes" : "", "notes" : "",
"summary" : "Logs user into the system", "summary" : "Logs user into the system",
"method": "GET", "method": "GET",
"params" : [param.query("username", "The user name for login", "string", true, false, ""),param.query("password", "The password for login in clear text", "string", true, false, "")].concat([]).concat([]).concat([]), "params" : [swagger.queryParam("username", "The user name for login", "string", true, false, ""),swagger.queryParam("password", "The password for login in clear text", "string", true, false, "")].concat([]).concat([]).concat([]),
"responseClass" : "String", "responseClass" : "String",
"errorResponses" : [swe.invalid('id'), swe.notFound('String')], "errorResponses" : [errors.invalid('id'), errors.notFound('String')],
"nickname" : "loginUser" "nickname" : "loginUser"
}, },
'action': function (req,res) { 'action': function (req,res) {
if (!req.params.username) { if (!req.params.username) {
throw swe.invalid('username'); throw errors.invalid('username');
} }
if (!req.params.password) { if (!req.params.password) {
throw swe.invalid('password'); throw errors.invalid('password');
} }
writeResponse(res, {message: "how about implementing loginUser as a GET method?"}); writeResponse(res, {message: "how about implementing loginUser as a GET method?"});
} }
@ -167,7 +166,7 @@ exports.logoutUser = {
"method": "GET", "method": "GET",
"params" : [].concat([]).concat([]).concat([]), "params" : [].concat([]).concat([]).concat([]),
"responseClass" : "", "responseClass" : "",
"errorResponses" : [swe.invalid('id'), swe.notFound('')], "errorResponses" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "logoutUser" "nickname" : "logoutUser"
}, },
'action': function (req,res) { 'action': function (req,res) {

View File

@ -1,26 +1,26 @@
var express = require("express") var express = require("express")
, url = require("url") , url = require("url")
, swagger = require("./Common/node/swagger.js") , swagger = require("swagger-node-express")
, db = false , db = false
var app = express.createServer( var app = express();
function(req, res, next) { if (req.db === undefined) { req.db = db; } next(); });
app.use(express.bodyParser()); app.use(express.bodyParser());
swagger.setAppHandler(app); swagger.setAppHandler(app);
// resources for the demo // resources for the demo
var storeApi = require("./apis/StoreApi.js");
var petApi = require("./apis/PetApi.js"); var petApi = require("./apis/PetApi.js");
var storeApi = require("./apis/StoreApi.js");
var userApi = require("./apis/UserApi.js"); var userApi = require("./apis/UserApi.js");
swagger.addModels(models) swagger.addModels(models)
.addGET(storeApi.getOrderById)
.addDELETE(storeApi.deleteOrder)
.addPOST(storeApi.placeOrder)
.addGET(petApi.getPetById) .addGET(petApi.getPetById)
.addPOST(petApi.addPet) .addPOST(petApi.addPet)
.addPUT(petApi.updatePet) .addPUT(petApi.updatePet)
.addGET(petApi.findPetsByStatus) .addGET(petApi.findPetsByStatus)
.addGET(petApi.findPetsByTags) .addGET(petApi.findPetsByTags)
.addGET(storeApi.getOrderById)
.addDELETE(storeApi.deleteOrder)
.addPOST(storeApi.placeOrder)
.addPOST(userApi.createUsersWithArrayInput) .addPOST(userApi.createUsersWithArrayInput)
.addPOST(userApi.createUser) .addPOST(userApi.createUser)
.addPOST(userApi.createUsersWithListInput) .addPOST(userApi.createUsersWithListInput)

View File

@ -1,135 +1,2 @@
exports.models = { exports.models = {
"Pet": { "Pet": {"id":"Pet","name":"","properties":{"name":{"type":"string","required":false},"tags":{"type":"Array","required":false,"items":{"$ref":"Tag"}},"photoUrls":{"type":"Array","required":false,"items":{"type":"string"}},"id":{"type":"long","required":false},"status":{"type":"string","required":false,"description":"pet status in the store"},"category":{"type":"Category","required":false}}},"Category": {"id":"Category","name":"","properties":{"id":{"type":"long","required":false},"name":{"type":"string","required":false}}},"Tag": {"id":"Tag","name":"","properties":{"id":{"type":"long","required":false},"name":{"type":"string","required":false}}},"User": {"id":"User","name":"","properties":{"email":{"type":"string","required":false},"username":{"type":"string","required":false},"userStatus":{"type":"int","required":false,"description":"User Status"},"lastName":{"type":"string","required":false},"firstName":{"type":"string","required":false},"id":{"type":"long","required":false},"phone":{"type":"string","required":false},"password":{"type":"string","required":false}}},"Order": {"id":"Order","name":"","properties":{"shipDate":{"type":"Date","required":false},"quantity":{"type":"int","required":false},"petId":{"type":"long","required":false},"id":{"type":"long","required":false},"status":{"type":"string","required":false,"description":"Order Status"}}}}
"id" : "Pet",
"properties" : {
"id" : {
"type" : "long",
"required" : false
},
"tags" : {
"type" : "Array",
"required" : false,
"items" : {
"$ref" : "Tag"
}
},
"category" : {
"type" : "Category",
"required" : false
},
"status" : {
"type" : "string",
"required" : false,
"description" : "pet status in the store",
"allowableValues" : {
"values" : [ "available", "pending", "sold" ],
"valueType" : "LIST"
}
},
"name" : {
"type" : "string",
"required" : false
},
"photoUrls" : {
"type" : "Array",
"required" : false,
"items" : {
"type" : "string"
}
}
}
},"Category": {
"id" : "Category",
"properties" : {
"id" : {
"type" : "long",
"required" : false
},
"name" : {
"type" : "string",
"required" : false
}
}
},"Tag": {
"id" : "Tag",
"properties" : {
"id" : {
"type" : "long",
"required" : false
},
"name" : {
"type" : "string",
"required" : false
}
}
},"User": {
"id" : "User",
"properties" : {
"id" : {
"type" : "long",
"required" : false
},
"lastName" : {
"type" : "string",
"required" : false
},
"username" : {
"type" : "string",
"required" : false
},
"phone" : {
"type" : "string",
"required" : false
},
"email" : {
"type" : "string",
"required" : false
},
"userStatus" : {
"type" : "int",
"required" : false,
"description" : "User Status",
"allowableValues" : {
"values" : [ "1-registered", "2-active", "3-closed" ],
"valueType" : "LIST"
}
},
"firstName" : {
"type" : "string",
"required" : false
},
"password" : {
"type" : "string",
"required" : false
}
}
},"Order": {
"id" : "Order",
"properties" : {
"id" : {
"type" : "long",
"required" : false
},
"petId" : {
"type" : "long",
"required" : false
},
"status" : {
"type" : "string",
"required" : false,
"description" : "Order Status",
"allowableValues" : {
"values" : [ "placed", " approved", " delivered" ],
"valueType" : "LIST"
}
},
"quantity" : {
"type" : "int",
"required" : false
},
"shipDate" : {
"type" : "Date",
"required" : false
}
}
}}

View File

@ -11,6 +11,7 @@
"node": ">= 0.8.x" "node": ">= 0.8.x"
}, },
"dependencies": { "dependencies": {
"swagger-node-express": ">= 1.2.x",
"connect": ">= 1.8.x", "connect": ">= 1.8.x",
"express": "3.x" "express": "3.x"
} }