updated nodejs server to swagger-tools, supports 2.0 spec

This commit is contained in:
Tony Tam 2015-03-18 16:10:54 -07:00
parent dd78de1ed8
commit b6e5c55817
21 changed files with 1060 additions and 924 deletions

View File

@ -1,110 +1,170 @@
package com.wordnik.swagger.codegen.languages; package com.wordnik.swagger.codegen.languages;
import com.wordnik.swagger.codegen.*; import com.wordnik.swagger.codegen.*;
import com.wordnik.swagger.models.Model;
import com.wordnik.swagger.models.properties.*;
import com.wordnik.swagger.util.Json; import com.wordnik.swagger.util.Json;
import com.wordnik.swagger.models.properties.*;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.*;
import java.util.*; import java.util.*;
import java.io.File; import java.io.File;
public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig { public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "com.wordnik.client"; protected String apiVersion = "1.0.0";
protected String groupId = "com.wordnik"; protected int serverPort = 8080;
protected String artifactId = "swagger-client"; protected String projectName = "swagger-server";
protected String artifactVersion = "1.0.0";
public String apiPackage() {
return "controllers";
}
/**
* Configures the type of generator.
*
* @return the CodegenType for this generator
* @see com.wordnik.swagger.codegen.CodegenType
*/
public CodegenType getTag() { public CodegenType getTag() {
return CodegenType.SERVER; return CodegenType.SERVER;
} }
/**
* Configures a friendly name for the generator. This will be used by the generator
* to select the library with the -l flag.
*
* @return the friendly name for the generator
*/
public String getName() { public String getName() {
return "nodejs"; return "nodejs";
} }
/**
* Returns human-friendly help for the generator. Provide the consumer with help
* tips, parameters here
*
* @return A string value for the help message
*/
public String getHelp() { public String getHelp() {
return "Generates a node.js server application compatible with the 1.2 swagger specification."; return "Generates a nodejs server library.";
} }
public NodeJSServerCodegen() { public NodeJSServerCodegen() {
super(); super();
// set the output folder here
outputFolder = "generated-code/nodejs"; outputFolder = "generated-code/nodejs";
apiTemplateFiles.put("api.mustache", ".js");
/**
* Models. You can write model files using the modelTemplateFiles map.
* if you want to create one template for file, you can do so here.
* for multiple files for model, just put another entry in the `modelTemplateFiles` with
* a different extension
*/
modelTemplateFiles.clear();
/**
* Api classes. You can write classes for each Api file with the apiTemplateFiles map.
* as with models, add multiple entries with different extensions for multiple files per
* class
*/
apiTemplateFiles.put(
"controller.mustache", // the template to use
".js"); // the extension for each file to write
/**
* Template Location. This is the location which templates will be read from. The generator
* will use the resource stream to attempt to read the templates.
*/
templateDir = "nodejs"; templateDir = "nodejs";
apiPackage = "app.apis";
modelPackage = "app";
additionalProperties.put("invokerPackage", invokerPackage); /**
additionalProperties.put("groupId", groupId); * Reserved words. Override this with reserved words specific to your language
additionalProperties.put("artifactId", artifactId); */
additionalProperties.put("artifactVersion", artifactVersion); reservedWords = new HashSet<String> (
supportingFiles.add(new SupportingFile("package.mustache", "", "package.json"));
supportingFiles.add(new SupportingFile("models.mustache", modelPackage, "models.js"));
supportingFiles.add(new SupportingFile("main.mustache", "", "main.js"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList( Arrays.asList(
"String", "break", "case", "class", "catch", "const", "continue", "debugger",
"boolean", "default", "delete", "do", "else", "export", "extends", "finally",
"Boolean", "for", "function", "if", "import", "in", "instanceof", "let", "new",
"Double", "return", "super", "switch", "this", "throw", "try", "typeof", "var",
"Integer", "void", "while", "with", "yield")
"Long", );
"Float")
/**
* Additional Properties. These values can be passed to the templates and
* are available in models, apis, and supporting files
*/
additionalProperties.put("apiVersion", apiVersion);
additionalProperties.put("serverPort", serverPort);
/**
* Supporting Files. You can write single files for the generator with the
* entire object tree available. If the input file has a suffix of `.mustache
* it will be processed by the template engine. Otherwise, it will be copied
*/
// supportingFiles.add(new SupportingFile("controller.mustache",
// "controllers",
// "controller.js")
// );
supportingFiles.add(new SupportingFile("swagger.mustache",
"api",
"swagger.json")
);
supportingFiles.add(new SupportingFile("index.mustache",
"",
"index.js")
);
supportingFiles.add(new SupportingFile("package.mustache",
"",
"package.json")
); );
typeMapping.put("array", "array");
} }
@Override
public String toApiName(String name) {
if(name.length() == 0)
return "DefaultController";
return initialCaps(name);
}
@Override
public String toApiFilename(String name) {
return toApiName(name);
}
/**
* Escapes a reserved word as defined in the `reservedWords` array. Handle escaping
* those terms here. This logic is only called if a variable matches the reseved words
*
* @return the escaped term
*/
@Override @Override
public String escapeReservedWord(String name) { public String escapeReservedWord(String name) {
return "_" + name; return "_" + name; // add an underscore to the name
}
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
List<Map<String, Object>> o = (List<Map<String, Object>>)objs.get("models");
for(Map<String, Object> modelMap : o) {
try {
CodegenModel m = (CodegenModel) modelMap.get("model");
ObjectNode on = (ObjectNode) Json.mapper().readTree(m.modelJson);
// inject the id field
on.put("id", m.name);
// remove the definitions qualifier with this nasty hack
m.modelJson = Json.pretty(on).replaceAll("\"#/definitions/", "\"");
}
catch (Exception e) {
e.printStackTrace();
// skip conversion
}
}
return objs;
} }
/**
* Location to write api files. You can use the apiPackage() as defined when the class is
* instantiated
*/
@Override @Override
public String apiFileFolder() { public String apiFileFolder() {
return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar); return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar);
} }
public String modelFileFolder() {
return outputFolder + File.separator + modelPackage().replace('.', File.separatorChar);
}
@Override @Override
public String getSwaggerType(Property p) { public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
String swaggerType = super.getSwaggerType(p); Map<String, Object> objectMap = (Map<String, Object>)objs.get("operations");
String type = null; List<CodegenOperation> operations = (List<CodegenOperation>)objectMap.get("operation");
if(typeMapping.containsKey(swaggerType)) { for(CodegenOperation operation : operations) {
return typeMapping.get(swaggerType); operation.httpMethod = operation.httpMethod.toLowerCase();
List<CodegenParameter> params = operation.allParams;
if(params != null && params.size() == 0)
operation.allParams = null;
List<CodegenResponse> responses = operation.responses;
if(responses != null) {
for(CodegenResponse resp : responses) {
if("0".equals(resp.code))
resp.code = "default";
} }
else }
type = swaggerType; }
return toModelName(type); return objs;
} }
} }

View File

@ -6,3 +6,19 @@ This server was generated by the [swagger-codegen](https://github.com/swagger-ap
This example uses the [expressjs](http://expressjs.com/) framework. To see how to make this your own, look here: This example uses the [expressjs](http://expressjs.com/) framework. To see how to make this your own, look here:
[README](https://github.com/wordnik/swagger-codegen/README.md) [README](https://github.com/wordnik/swagger-codegen/README.md)
### Running the server
To run the server, follow these simple steps:
```
npm install
node .
```
To view the Swagger UI interface:
```
open http://localhost:8080/docs
```
This project leverages the mega-awesome [swagger-tools](https://github.com/apigee-127/swagger-tools) middleware which does most all the work.

View File

@ -1,62 +0,0 @@
var swagger = require("swagger-node-express");
var url = require("url");
var errors = swagger.errors;
var params = swagger.params;
/* add model includes */
function writeResponse (response, data) {
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");
response.send(JSON.stringify(data));
}
exports.models = models = require("../models.js");
{{#operations}}
{{#operation}}
exports.{{nickname}} = {
'spec': {
"description" : "the {{baseName}} API",
"path" : "{{path}}",
"notes" : "{{{notes}}}",
"summary" : "{{{summary}}}",
"method": "{{httpMethod}}",
"params" : [{{#queryParams}}
params.query("{{paramName}}", "{{description}}", "{{swaggerDataType}}", {{#required}}true{{/required}}{{^required}}false{{/required}}, {{#allowMultiple}}true{{/allowMultiple}}{{^allowMultiple}}false{{/allowMultiple}}, "{{{allowableValues}}}"{{#defaultValue}}, {{{defaultValue}}}{{/defaultValue}}){{#hasMore}},{{/hasMore}}
{{/queryParams}}].concat([{{#pathParams}}
params.path("{{paramName}}", "{{description}}"){{#hasMore}},{{/hasMore}}
{{/pathParams}}]).concat([{{#headerParams}}
params.header("{{paramName}}", "{{description}}"){{#hasMore}},{{/hasMore}}
{{/headerParams}}]).concat([{{#bodyParams}}
params.body("body", "{{swaggerDataType}}", "{{description}}", {{#required}}{{required}}{{/required}}{{^required}}false{{/required}})
{{/bodyParams}}]),
{{#returnContainer}}
"type": "{{returnType}}",
"items": {
{{#returnTypeIsPrimitive}}"type": "{{returnContainer}}"{{/returnTypeIsPrimitive}}
{{^returnTypeIsPrimitive}}"$ref": "{{returnContainer}}"{{/returnTypeIsPrimitive}}
},
// container
{{/returnContainer}}
{{^returnContainer}}
"type" : "{{returnType}}",
{{/returnContainer}}
"responseMessages" : [errors.invalid('id'), errors.notFound('{{returnType}}')],
"nickname" : "{{nickname}}"
},
'action': function (req,res) {
{{#requiredParamCount}}
{{#requiredParams}}
if (!req.params.{{baseName}}) {
throw errors.invalid('{{baseName}}');
}
{{/requiredParams}}
{{/requiredParamCount}}
writeResponse(res, {message: "how about implementing {{nickname}} as a {{httpMethod}} method?"});
}
};
{{/operation}}
{{/operations}}

View File

@ -0,0 +1,17 @@
'use strict';
var url = require('url');
{{#operations}}
{{#operation}}
module.exports.{{nickname}} = function {{nickname}} (req, res, next) {
{{#allParams}}var {{paramName}} = req.swagger.params['{{baseName}}'].value;
{{/allParams}}
console.log('do some magic!');
res.setHeader('Content-Type', 'application/json');
res.end();
};
{{/operation}}
{{/operations}}

View File

@ -0,0 +1,38 @@
'use strict';
var app = require('connect')();
var http = require('http');
var swaggerTools = require('swagger-tools');
var serverPort = {{serverPort}};
// swaggerRouter configuration
var options = {
swaggerUi: '/swagger.json',
controllers: './controllers',
useStubs: process.env.NODE_ENV === 'development' ? true : false // Conditionally turn on stubs (mock mode)
};
// The Swagger document (require it, build it programmatically, fetch it from a URL, ...)
var swaggerDoc = require('./api/swagger.json');
// Initialize the Swagger middleware
swaggerTools.initializeMiddleware(swaggerDoc, function (middleware) {
// Interpret Swagger resources and attach metadata to request - must be first in swagger-tools middleware chain
app.use(middleware.swaggerMetadata());
// Validate Swagger requests
app.use(middleware.swaggerValidator());
// Route validated requests to appropriate controller
app.use(middleware.swaggerRouter(options));
// Serve the Swagger documents and Swagger UI
app.use(middleware.swaggerUi());
// Start the server
http.createServer(app).listen({{serverPort}}, function () {
console.log('Your server is listening on port %d (http://localhost:%d)', {{serverPort}}, {{serverPort}});
console.log('Swagger-ui is available on http://localhost:%d/docs', {{serverPort}});
});
});

View File

@ -1,53 +0,0 @@
var express = require("express")
, url = require("url")
, cors = require("cors")
, app = express()
, swagger = require("swagger-node-express")
, db = false
var corsOptions = {
credentials: true,
origin: function(origin,callback) {
if(origin===undefined) {
callback(null,false);
} else {
callback(null,true);
}
}
};
app.use(express.json());
app.use(express.urlencoded());
app.use(cors(corsOptions));
{{#basePath}}
var subpath = express();
app.use("{{{basePath}}}", subpath);
swagger.setAppHandler(subpath);
{{/basePath}}
{{^basePath}}
swagger.setAppHandler(app);
{{/basePath}}
swagger.configureSwaggerPaths("", "api-docs", "")
var models = require("./app/models.js");
{{#apiInfo}}
{{#apis}}
var {{classname}} = require("./{{apiFolder}}/{{classname}}.js");
{{/apis}}
{{/apiInfo}}
swagger.addModels(models)
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}.add{{httpMethod}}({{classname}}.{{nickname}})
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}};
// configures the app
swagger.configure("http://localhost:8002{{basePath}}", "0.1");
// start the server
app.listen(8002);

View File

@ -1,3 +0,0 @@
exports.models = {
{{#models}}{{#model}}"{{classVarName}}": {{{modelJson}}}{{#hasMoreModels}},{{/hasMoreModels}}{{/model}}{{/models}}
}

View File

@ -1,16 +1,15 @@
{ {
"name": "{{{artifactId}}}", "name": "{{projectName}}",
"description": "Wordnik node.js server generator", "version": "{{appVersion}}",
"version": "{{{artifactVersion}}}", "description": "{{appDescription}}",
"homepage": "{{{homepage}}}", "main": "index.js",
"main": "./main.js", "keywords": [
"engines": { "swagger"
"node": ">= 0.8.x" ],
}, "license": "MIT",
"private": true,
"dependencies": { "dependencies": {
"swagger-node-express": ">= 2.0.x", "connect": "^3.2.0",
"connect": ">= 1.8.x", "swagger-tools": "0.8.*"
"cors": "2.1.1",
"express": "3.x"
} }
} }

View File

@ -0,0 +1,42 @@
{
"swagger": "2.0",
"info": {
"title": "{{appName}}",
"description": "{{appDescription}}",
"version": "{{apiVersion}}"
},
{{#apiInfo}}
"produces": ["application/json"],
"host": "{{host}}",
"basePath": "{{contextPath}}",
"paths": {
{{#apis}}
{{#operations}}
{{#operation}}
"{{{path}}}": {
"{{httpMethod}}": {
"x-swagger-router-controller": "{{classname}}",
"tags": ["{{baseName}}"],
"operationId": "{{operationId}}",{{#hasParams}}
"parameters": [
{{#allParams}}
{{{jsonSchema}}}{{#hasMore}},{{/hasMore}}
{{/allParams}}
],{{/hasParams}}
"responses": {
{{#responses}}
"{{code}}": {{{jsonSchema}}}
{{#hasMore}},{{/hasMore}}
{{/responses}}
}
}
} {{#hasMore}},{{/hasMore}}
{{/operation}}
{{#hasMore}},{{/hasMore}}
{{/operations}}
{{/apis}}
{{/apiInfo}}
}, "definitions": {
{{#models}}{{#model}}"{{classVarName}}": {{{modelJson}}}{{#hasMoreModels}},{{/hasMoreModels}}{{/model}}{{/models}}
}
}

View File

@ -1,8 +0,0 @@
# Swagger generated server
## Overview
This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [swagger-spec](https://github.com/swagger-api/swagger-spec) from a remote server, you can easily generate a server stub. This is an example of building a node.js server.
This example uses the [expressjs](http://expressjs.com/) framework. To see how to make this your own, look here:
[README](https://github.com/wordnik/swagger-codegen/README.md)

View File

@ -0,0 +1,559 @@
{
"swagger": "2.0",
"info": {
"title": "Swagger Petstore",
"description": "This is a sample server Petstore server. You can find out more about Swagger at &lt;a href=&quot;http://swagger.io&quot;&gt;http://swagger.io&lt;/a&gt; or on irc.freenode.net, #swagger. For this sample, you can use the api key &quot;special-key&quot; to test the authorization filters",
"version": "1.0.0"
},
"produces": [
"application/json"
],
"host": "petstore.swagger.io",
"basePath": "/v2",
"paths": {
"/user": {
"post": {
"x-swagger-router-controller": "User",
"tags": [
"User"
],
"operationId": "createUser",
"parameters": [
{
"in": "body",
"name": "body",
"description": "Created user object",
"required": false,
"schema": {
"$ref": "#/definitions/User"
}
}
],
"responses": {
"default": {
"description": "successful operation"
}
}
}
},
"/user/createWithArray": {
"post": {
"x-swagger-router-controller": "User",
"tags": [
"User"
],
"operationId": "createUsersWithArrayInput",
"parameters": [
{
"in": "body",
"name": "body",
"description": "List of user object",
"required": false,
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/User"
}
}
}
],
"responses": {
"default": {
"description": "successful operation"
}
}
}
},
"/user/createWithList": {
"post": {
"x-swagger-router-controller": "User",
"tags": [
"User"
],
"operationId": "createUsersWithListInput",
"parameters": [
{
"in": "body",
"name": "body",
"description": "List of user object",
"required": false,
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/User"
}
}
}
],
"responses": {
"default": {
"description": "successful operation"
}
}
}
},
"/user/login": {
"get": {
"x-swagger-router-controller": "User",
"tags": [
"User"
],
"operationId": "loginUser",
"parameters": [
{
"name": "username",
"in": "query",
"description": "The user name for login",
"required": false,
"type": "string"
},
{
"name": "password",
"in": "query",
"description": "The password for login in clear text",
"required": false,
"type": "string"
}
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"type": "string"
}
},
"400": {
"description": "Invalid username/password supplied"
}
}
}
},
"/user/logout": {
"get": {
"x-swagger-router-controller": "User",
"tags": [
"User"
],
"operationId": "logoutUser",
"responses": {
"default": {
"description": "successful operation"
}
}
}
},
"/user/{username}": {
"delete": {
"x-swagger-router-controller": "User",
"tags": [
"User"
],
"operationId": "deleteUser",
"parameters": [
{
"name": "username",
"in": "path",
"description": "The name that needs to be deleted",
"required": true,
"type": "string"
}
],
"responses": {
"404": {
"description": "User not found"
},
"400": {
"description": "Invalid username supplied"
}
}
}
},
"/pet": {
"post": {
"x-swagger-router-controller": "Pet",
"tags": [
"Pet"
],
"operationId": "addPet",
"parameters": [
{
"in": "body",
"name": "body",
"description": "Pet object that needs to be added to the store",
"required": false,
"schema": {
"$ref": "#/definitions/Pet"
}
}
],
"responses": {
"405": {
"description": "Invalid input"
}
}
}
},
"/pet/findByStatus": {
"get": {
"x-swagger-router-controller": "Pet",
"tags": [
"Pet"
],
"operationId": "findPetsByStatus",
"parameters": [
{
"name": "status",
"in": "query",
"description": "Status values that need to be considered for filter",
"required": false,
"type": "array",
"items": {
"type": "string"
},
"collectionFormat": "multi",
"default": "available"
}
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Pet"
}
}
},
"400": {
"description": "Invalid status value"
}
}
}
},
"/pet/findByTags": {
"get": {
"x-swagger-router-controller": "Pet",
"tags": [
"Pet"
],
"operationId": "findPetsByTags",
"parameters": [
{
"name": "tags",
"in": "query",
"description": "Tags to filter by",
"required": false,
"type": "array",
"items": {
"type": "string"
},
"collectionFormat": "multi"
}
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Pet"
}
}
},
"400": {
"description": "Invalid tag value"
}
}
}
},
"/pet/{petId}": {
"delete": {
"x-swagger-router-controller": "Pet",
"tags": [
"Pet"
],
"operationId": "deletePet",
"parameters": [
{
"name": "api_key",
"in": "header",
"description": "",
"required": false,
"type": "string"
},
{
"name": "petId",
"in": "path",
"description": "Pet id to delete",
"required": true,
"type": "integer",
"format": "int64"
}
],
"responses": {
"400": {
"description": "Invalid pet value"
}
}
}
},
"/pet/{petId}/uploadImage": {
"post": {
"x-swagger-router-controller": "Pet",
"tags": [
"Pet"
],
"operationId": "uploadFile",
"parameters": [
{
"name": "petId",
"in": "path",
"description": "ID of pet to update",
"required": true,
"type": "integer",
"format": "int64"
},
{
"name": "additionalMetadata",
"in": "formData",
"description": "Additional data to pass to server",
"required": false,
"type": "string"
},
{
"name": "file",
"in": "formData",
"description": "file to upload",
"required": false,
"type": "file"
}
],
"responses": {
"default": {
"description": "successful operation"
}
}
}
},
"/store/inventory": {
"get": {
"x-swagger-router-controller": "Store",
"tags": [
"Store"
],
"operationId": "getInventory",
"responses": {
"200": {
"description": "successful operation",
"schema": {
"type": "object",
"additionalProperties": {
"type": "integer",
"format": "int32"
}
}
}
}
}
},
"/store/order": {
"post": {
"x-swagger-router-controller": "Store",
"tags": [
"Store"
],
"operationId": "placeOrder",
"parameters": [
{
"in": "body",
"name": "body",
"description": "order placed for purchasing the pet",
"required": false,
"schema": {
"$ref": "#/definitions/Order"
}
}
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"$ref": "#/definitions/Order"
}
},
"400": {
"description": "Invalid Order"
}
}
}
},
"/store/order/{orderId}": {
"delete": {
"x-swagger-router-controller": "Store",
"tags": [
"Store"
],
"operationId": "deleteOrder",
"parameters": [
{
"name": "orderId",
"in": "path",
"description": "ID of the order that needs to be deleted",
"required": true,
"type": "string"
}
],
"responses": {
"404": {
"description": "Order not found"
},
"400": {
"description": "Invalid ID supplied"
}
}
}
}
},
"definitions": {
"User": {
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"username": {
"type": "string"
},
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"email": {
"type": "string"
},
"password": {
"type": "string"
},
"phone": {
"type": "string"
},
"userStatus": {
"type": "integer",
"format": "int32",
"description": "User Status"
}
},
"xml": {
"name": "User"
}
},
"Category": {
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"name": {
"type": "string"
}
},
"xml": {
"name": "Category"
}
},
"Pet": {
"required": [
"name",
"photoUrls"
],
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"category": {
"$ref": "#/definitions/Category"
},
"name": {
"type": "string",
"example": "doggie"
},
"photoUrls": {
"type": "array",
"items": {
"type": "string"
}
},
"tags": {
"type": "array",
"items": {
"$ref": "#/definitions/Tag"
}
},
"status": {
"type": "string",
"description": "pet status in the store",
"enum": [
"available",
"pending",
"sold"
]
}
},
"xml": {
"name": "Pet"
}
},
"Tag": {
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"name": {
"type": "string"
}
},
"xml": {
"name": "Tag"
}
},
"Order": {
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"petId": {
"type": "integer",
"format": "int64"
},
"quantity": {
"type": "integer",
"format": "int32"
},
"shipDate": {
"type": "string",
"format": "date-time"
},
"status": {
"type": "string",
"description": "Order Status",
"enum": [
"placed",
"approved",
"delivered"
]
},
"complete": {
"type": "boolean"
}
},
"xml": {
"name": "Order"
}
}
}
}

View File

@ -1,203 +0,0 @@
var swagger = require("swagger-node-express");
var url = require("url");
var errors = swagger.errors;
var params = swagger.params;
/* add model includes */
function writeResponse (response, data) {
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");
response.send(JSON.stringify(data));
}
exports.models = models = require("../models.js");
exports.updatePet = {
'spec': {
"description" : "Operations about pets",
"path" : "/pet",
"notes" : "",
"summary" : "Update an existing pet",
"method": "PUT",
"params" : [].concat([]).concat([]).concat([
params.body("body", "", "Pet object that needs to be added to the store", false)
]),
"type" : "",
"responseMessages" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "updatePet"
},
'action': function (req,res) {
writeResponse(res, {message: "how about implementing updatePet as a PUT method?"});
}
};
exports.addPet = {
'spec': {
"description" : "Operations about pets",
"path" : "/pet",
"notes" : "",
"summary" : "Add a new pet to the store",
"method": "POST",
"params" : [].concat([]).concat([]).concat([
params.body("body", "", "Pet object that needs to be added to the store", false)
]),
"type" : "",
"responseMessages" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "addPet"
},
'action': function (req,res) {
writeResponse(res, {message: "how about implementing addPet as a POST method?"});
}
};
exports.findPetsByStatus = {
'spec': {
"description" : "Operations about pets",
"path" : "/pet/findByStatus",
"notes" : "Multiple status values can be provided with comma seperated strings",
"summary" : "Finds Pets by status",
"method": "GET",
"params" : [
params.query("status", "Status values that need to be considered for filter", "", false, false, "")
].concat([]).concat([]).concat([]),
"type": "array",
"items": {
"$ref": "array"
},
// container
"responseMessages" : [errors.invalid('id'), errors.notFound('array')],
"nickname" : "findPetsByStatus"
},
'action': function (req,res) {
writeResponse(res, {message: "how about implementing findPetsByStatus as a GET method?"});
}
};
exports.findPetsByTags = {
'spec': {
"description" : "Operations about pets",
"path" : "/pet/findByTags",
"notes" : "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.",
"summary" : "Finds Pets by tags",
"method": "GET",
"params" : [
params.query("tags", "Tags to filter by", "", false, false, "")
].concat([]).concat([]).concat([]),
"type": "array",
"items": {
"$ref": "array"
},
// container
"responseMessages" : [errors.invalid('id'), errors.notFound('array')],
"nickname" : "findPetsByTags"
},
'action': function (req,res) {
writeResponse(res, {message: "how about implementing findPetsByTags as a GET method?"});
}
};
exports.getPetById = {
'spec': {
"description" : "Operations about pets",
"path" : "/pet/{petId}",
"notes" : "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions",
"summary" : "Find pet by ID",
"method": "GET",
"params" : [].concat([
params.path("petId", "ID of pet that needs to be fetched")
]).concat([]).concat([]),
"type" : "Pet",
"responseMessages" : [errors.invalid('id'), errors.notFound('Pet')],
"nickname" : "getPetById"
},
'action': function (req,res) {
writeResponse(res, {message: "how about implementing getPetById as a GET method?"});
}
};
exports.updatePetWithForm = {
'spec': {
"description" : "Operations about pets",
"path" : "/pet/{petId}",
"notes" : "",
"summary" : "Updates a pet in the store with form data",
"method": "POST",
"params" : [].concat([
params.path("petId", "ID of pet that needs to be updated")
]).concat([]).concat([]),
"type" : "",
"responseMessages" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "updatePetWithForm"
},
'action': function (req,res) {
writeResponse(res, {message: "how about implementing updatePetWithForm as a POST method?"});
}
};
exports.deletePet = {
'spec': {
"description" : "Operations about pets",
"path" : "/pet/{petId}",
"notes" : "",
"summary" : "Deletes a pet",
"method": "DELETE",
"params" : [].concat([
params.path("petId", "Pet id to delete")
]).concat([
params.header("api_key", "")
]).concat([]),
"type" : "",
"responseMessages" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "deletePet"
},
'action': function (req,res) {
writeResponse(res, {message: "how about implementing deletePet as a DELETE method?"});
}
};
exports.uploadFile = {
'spec': {
"description" : "Operations about pets",
"path" : "/pet/{petId}/uploadImage",
"notes" : "",
"summary" : "uploads an image",
"method": "POST",
"params" : [].concat([]).concat([]).concat([]),
"type" : "",
"responseMessages" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "uploadFile"
},
'action': function (req,res) {
writeResponse(res, {message: "how about implementing uploadFile as a POST method?"});
}
};

View File

@ -1,108 +0,0 @@
var swagger = require("swagger-node-express");
var url = require("url");
var errors = swagger.errors;
var params = swagger.params;
/* add model includes */
function writeResponse (response, data) {
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");
response.send(JSON.stringify(data));
}
exports.models = models = require("../models.js");
exports.getInventory = {
'spec': {
"description" : "Operations about pets",
"path" : "/store/inventory",
"notes" : "Returns a map of status codes to quantities",
"summary" : "Returns pet inventories by status",
"method": "GET",
"params" : [].concat([]).concat([]).concat([]),
"type": "Map",
"items": {
"$ref": "map"
},
// container
"responseMessages" : [errors.invalid('id'), errors.notFound('Map')],
"nickname" : "getInventory"
},
'action': function (req,res) {
writeResponse(res, {message: "how about implementing getInventory as a GET method?"});
}
};
exports.placeOrder = {
'spec': {
"description" : "Operations about pets",
"path" : "/store/order",
"notes" : "",
"summary" : "Place an order for a pet",
"method": "POST",
"params" : [].concat([]).concat([]).concat([
params.body("body", "", "order placed for purchasing the pet", false)
]),
"type" : "Order",
"responseMessages" : [errors.invalid('id'), errors.notFound('Order')],
"nickname" : "placeOrder"
},
'action': function (req,res) {
writeResponse(res, {message: "how about implementing placeOrder as a POST method?"});
}
};
exports.getOrderById = {
'spec': {
"description" : "Operations about pets",
"path" : "/store/order/{orderId}",
"notes" : "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions",
"summary" : "Find purchase order by ID",
"method": "GET",
"params" : [].concat([
params.path("orderId", "ID of pet that needs to be fetched")
]).concat([]).concat([]),
"type" : "Order",
"responseMessages" : [errors.invalid('id'), errors.notFound('Order')],
"nickname" : "getOrderById"
},
'action': function (req,res) {
writeResponse(res, {message: "how about implementing getOrderById as a GET method?"});
}
};
exports.deleteOrder = {
'spec': {
"description" : "Operations about pets",
"path" : "/store/order/{orderId}",
"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",
"method": "DELETE",
"params" : [].concat([
params.path("orderId", "ID of the order that needs to be deleted")
]).concat([]).concat([]),
"type" : "",
"responseMessages" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "deleteOrder"
},
'action': function (req,res) {
writeResponse(res, {message: "how about implementing deleteOrder as a DELETE method?"});
}
};

View File

@ -1,195 +0,0 @@
var swagger = require("swagger-node-express");
var url = require("url");
var errors = swagger.errors;
var params = swagger.params;
/* add model includes */
function writeResponse (response, data) {
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");
response.send(JSON.stringify(data));
}
exports.models = models = require("../models.js");
exports.createUser = {
'spec': {
"description" : "Operations about pets",
"path" : "/user",
"notes" : "This can only be done by the logged in user.",
"summary" : "Create user",
"method": "POST",
"params" : [].concat([]).concat([]).concat([
params.body("body", "", "Created user object", false)
]),
"type" : "",
"responseMessages" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "createUser"
},
'action': function (req,res) {
writeResponse(res, {message: "how about implementing createUser as a POST method?"});
}
};
exports.createUsersWithArrayInput = {
'spec': {
"description" : "Operations about pets",
"path" : "/user/createWithArray",
"notes" : "",
"summary" : "Creates list of users with given input array",
"method": "POST",
"params" : [].concat([]).concat([]).concat([
params.body("body", "", "List of user object", false)
]),
"type" : "",
"responseMessages" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "createUsersWithArrayInput"
},
'action': function (req,res) {
writeResponse(res, {message: "how about implementing createUsersWithArrayInput as a POST method?"});
}
};
exports.createUsersWithListInput = {
'spec': {
"description" : "Operations about pets",
"path" : "/user/createWithList",
"notes" : "",
"summary" : "Creates list of users with given input array",
"method": "POST",
"params" : [].concat([]).concat([]).concat([
params.body("body", "", "List of user object", false)
]),
"type" : "",
"responseMessages" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "createUsersWithListInput"
},
'action': function (req,res) {
writeResponse(res, {message: "how about implementing createUsersWithListInput as a POST method?"});
}
};
exports.loginUser = {
'spec': {
"description" : "Operations about pets",
"path" : "/user/login",
"notes" : "",
"summary" : "Logs user into the system",
"method": "GET",
"params" : [
params.query("username", "The user name for login", "", false, false, ""),
params.query("password", "The password for login in clear text", "", false, false, "")
].concat([]).concat([]).concat([]),
"type" : "String",
"responseMessages" : [errors.invalid('id'), errors.notFound('String')],
"nickname" : "loginUser"
},
'action': function (req,res) {
writeResponse(res, {message: "how about implementing loginUser as a GET method?"});
}
};
exports.logoutUser = {
'spec': {
"description" : "Operations about pets",
"path" : "/user/logout",
"notes" : "",
"summary" : "Logs out current logged in user session",
"method": "GET",
"params" : [].concat([]).concat([]).concat([]),
"type" : "",
"responseMessages" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "logoutUser"
},
'action': function (req,res) {
writeResponse(res, {message: "how about implementing logoutUser as a GET method?"});
}
};
exports.getUserByName = {
'spec': {
"description" : "Operations about pets",
"path" : "/user/{username}",
"notes" : "",
"summary" : "Get user by user name",
"method": "GET",
"params" : [].concat([
params.path("username", "The name that needs to be fetched. Use user1 for testing. ")
]).concat([]).concat([]),
"type" : "User",
"responseMessages" : [errors.invalid('id'), errors.notFound('User')],
"nickname" : "getUserByName"
},
'action': function (req,res) {
writeResponse(res, {message: "how about implementing getUserByName as a GET method?"});
}
};
exports.updateUser = {
'spec': {
"description" : "Operations about pets",
"path" : "/user/{username}",
"notes" : "This can only be done by the logged in user.",
"summary" : "Updated user",
"method": "PUT",
"params" : [].concat([
params.path("username", "name that need to be deleted")
]).concat([]).concat([
params.body("body", "", "Updated user object", false)
]),
"type" : "",
"responseMessages" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "updateUser"
},
'action': function (req,res) {
writeResponse(res, {message: "how about implementing updateUser as a PUT method?"});
}
};
exports.deleteUser = {
'spec': {
"description" : "Operations about pets",
"path" : "/user/{username}",
"notes" : "This can only be done by the logged in user.",
"summary" : "Delete user",
"method": "DELETE",
"params" : [].concat([
params.path("username", "The name that needs to be deleted")
]).concat([]).concat([]),
"type" : "",
"responseMessages" : [errors.invalid('id'), errors.notFound('')],
"nickname" : "deleteUser"
},
'action': function (req,res) {
writeResponse(res, {message: "how about implementing deleteUser as a DELETE method?"});
}
};

View File

@ -1,132 +0,0 @@
exports.models = {
"User": {
"properties" : {
"id" : {
"type" : "integer",
"format" : "int64"
},
"username" : {
"type" : "string"
},
"firstName" : {
"type" : "string"
},
"lastName" : {
"type" : "string"
},
"email" : {
"type" : "string"
},
"password" : {
"type" : "string"
},
"phone" : {
"type" : "string"
},
"userStatus" : {
"type" : "integer",
"format" : "int32",
"description" : "User Status"
}
},
"xml" : {
"name" : "User"
},
"id" : "User"
},"Category": {
"properties" : {
"id" : {
"type" : "integer",
"format" : "int64"
},
"name" : {
"type" : "string"
}
},
"xml" : {
"name" : "Category"
},
"id" : "Category"
},"Pet": {
"required" : [ "name", "photoUrls" ],
"properties" : {
"id" : {
"type" : "integer",
"format" : "int64"
},
"category" : {
"$ref" : "Category"
},
"name" : {
"type" : "string",
"example" : "doggie"
},
"photoUrls" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"tags" : {
"type" : "array",
"items" : {
"$ref" : "Tag"
}
},
"status" : {
"type" : "string",
"description" : "pet status in the store",
"enum" : [ "available", "pending", "sold" ]
}
},
"xml" : {
"name" : "Pet"
},
"id" : "Pet"
},"Tag": {
"properties" : {
"id" : {
"type" : "integer",
"format" : "int64"
},
"name" : {
"type" : "string"
}
},
"xml" : {
"name" : "Tag"
},
"id" : "Tag"
},"Order": {
"properties" : {
"id" : {
"type" : "integer",
"format" : "int64"
},
"petId" : {
"type" : "integer",
"format" : "int64"
},
"quantity" : {
"type" : "integer",
"format" : "int32"
},
"shipDate" : {
"type" : "string",
"format" : "date-time"
},
"status" : {
"type" : "string",
"description" : "Order Status",
"enum" : [ "placed", "approved", "delivered" ]
},
"complete" : {
"type" : "boolean"
}
},
"xml" : {
"name" : "Order"
},
"id" : "Order"
}
}

View File

@ -0,0 +1,81 @@
'use strict';
var url = require('url');
module.exports.updatePet = function updatePet (req, res, next) {
var body = req.swagger.params['body'].value;
console.log('do some magic!');
res.setHeader('Content-Type', 'application/json');
res.end();
};
module.exports.addPet = function addPet (req, res, next) {
var body = req.swagger.params['body'].value;
console.log('do some magic!');
res.setHeader('Content-Type', 'application/json');
res.end();
};
module.exports.findPetsByStatus = function findPetsByStatus (req, res, next) {
var status = req.swagger.params['status'].value;
console.log('do some magic!');
res.setHeader('Content-Type', 'application/json');
res.end();
};
module.exports.findPetsByTags = function findPetsByTags (req, res, next) {
var tags = req.swagger.params['tags'].value;
console.log('do some magic!');
res.setHeader('Content-Type', 'application/json');
res.end();
};
module.exports.getPetById = function getPetById (req, res, next) {
var petId = req.swagger.params['petId'].value;
console.log('do some magic!');
res.setHeader('Content-Type', 'application/json');
res.end();
};
module.exports.updatePetWithForm = function updatePetWithForm (req, res, next) {
var petId = req.swagger.params['petId'].value;
var name = req.swagger.params['name'].value;
var status = req.swagger.params['status'].value;
console.log('do some magic!');
res.setHeader('Content-Type', 'application/json');
res.end();
};
module.exports.deletePet = function deletePet (req, res, next) {
var api_key = req.swagger.params['api_key'].value;
var petId = req.swagger.params['petId'].value;
console.log('do some magic!');
res.setHeader('Content-Type', 'application/json');
res.end();
};
module.exports.uploadFile = function uploadFile (req, res, next) {
var petId = req.swagger.params['petId'].value;
var additionalMetadata = req.swagger.params['additionalMetadata'].value;
var file = req.swagger.params['file'].value;
console.log('do some magic!');
res.setHeader('Content-Type', 'application/json');
res.end();
};

View File

@ -0,0 +1,39 @@
'use strict';
var url = require('url');
module.exports.getInventory = function getInventory (req, res, next) {
console.log('do some magic!');
res.setHeader('Content-Type', 'application/json');
res.end();
};
module.exports.placeOrder = function placeOrder (req, res, next) {
var body = req.swagger.params['body'].value;
console.log('do some magic!');
res.setHeader('Content-Type', 'application/json');
res.end();
};
module.exports.getOrderById = function getOrderById (req, res, next) {
var orderId = req.swagger.params['orderId'].value;
console.log('do some magic!');
res.setHeader('Content-Type', 'application/json');
res.end();
};
module.exports.deleteOrder = function deleteOrder (req, res, next) {
var orderId = req.swagger.params['orderId'].value;
console.log('do some magic!');
res.setHeader('Content-Type', 'application/json');
res.end();
};

View File

@ -0,0 +1,77 @@
'use strict';
var url = require('url');
module.exports.createUser = function createUser (req, res, next) {
var body = req.swagger.params['body'].value;
console.log('do some magic!');
res.setHeader('Content-Type', 'application/json');
res.end();
};
module.exports.createUsersWithArrayInput = function createUsersWithArrayInput (req, res, next) {
var body = req.swagger.params['body'].value;
console.log('do some magic!');
res.setHeader('Content-Type', 'application/json');
res.end();
};
module.exports.createUsersWithListInput = function createUsersWithListInput (req, res, next) {
var body = req.swagger.params['body'].value;
console.log('do some magic!');
res.setHeader('Content-Type', 'application/json');
res.end();
};
module.exports.loginUser = function loginUser (req, res, next) {
var username = req.swagger.params['username'].value;
var password = req.swagger.params['password'].value;
console.log('do some magic!');
res.setHeader('Content-Type', 'application/json');
res.end();
};
module.exports.logoutUser = function logoutUser (req, res, next) {
console.log('do some magic!');
res.setHeader('Content-Type', 'application/json');
res.end();
};
module.exports.getUserByName = function getUserByName (req, res, next) {
var username = req.swagger.params['username'].value;
console.log('do some magic!');
res.setHeader('Content-Type', 'application/json');
res.end();
};
module.exports.updateUser = function updateUser (req, res, next) {
var username = req.swagger.params['username'].value;
var body = req.swagger.params['body'].value;
console.log('do some magic!');
res.setHeader('Content-Type', 'application/json');
res.end();
};
module.exports.deleteUser = function deleteUser (req, res, next) {
var username = req.swagger.params['username'].value;
console.log('do some magic!');
res.setHeader('Content-Type', 'application/json');
res.end();
};

View File

@ -0,0 +1,38 @@
'use strict';
var app = require('connect')();
var http = require('http');
var swaggerTools = require('swagger-tools');
var serverPort = 8080;
// swaggerRouter configuration
var options = {
swaggerUi: '/swagger.json',
controllers: './controllers',
useStubs: process.env.NODE_ENV === 'development' ? true : false // Conditionally turn on stubs (mock mode)
};
// The Swagger document (require it, build it programmatically, fetch it from a URL, ...)
var swaggerDoc = require('./api/swagger.json');
// Initialize the Swagger middleware
swaggerTools.initializeMiddleware(swaggerDoc, function (middleware) {
// Interpret Swagger resources and attach metadata to request - must be first in swagger-tools middleware chain
app.use(middleware.swaggerMetadata());
// Validate Swagger requests
app.use(middleware.swaggerValidator());
// Route validated requests to appropriate controller
app.use(middleware.swaggerRouter(options));
// Serve the Swagger documents and Swagger UI
app.use(middleware.swaggerUi());
// Start the server
http.createServer(app).listen(8080, function () {
console.log('Your server is listening on port %d (http://localhost:%d)', 8080, 8080);
console.log('Swagger-ui is available on http://localhost:%d/docs', 8080);
});
});

View File

@ -1,65 +0,0 @@
var express = require("express")
, url = require("url")
, cors = require("cors")
, app = express()
, swagger = require("swagger-node-express")
, db = false
var corsOptions = {
credentials: true,
origin: function(origin,callback) {
if(origin===undefined) {
callback(null,false);
} else {
callback(null,true);
}
}
};
app.use(express.json());
app.use(express.urlencoded());
app.use(cors(corsOptions));
var subpath = express();
app.use("/v2", subpath);
swagger.setAppHandler(subpath);
swagger.configureSwaggerPaths("", "api-docs", "")
var models = require("./app/models.js");
var UserApi = require("./app/apis/UserApi.js");
var StoreApi = require("./app/apis/StoreApi.js");
var PetApi = require("./app/apis/PetApi.js");
swagger.addModels(models)
.addPOST(UserApi.createUser)
.addPOST(UserApi.createUsersWithArrayInput)
.addPOST(UserApi.createUsersWithListInput)
.addGET(UserApi.loginUser)
.addGET(UserApi.logoutUser)
.addGET(UserApi.getUserByName)
.addPUT(UserApi.updateUser)
.addDELETE(UserApi.deleteUser)
.addGET(StoreApi.getInventory)
.addPOST(StoreApi.placeOrder)
.addGET(StoreApi.getOrderById)
.addDELETE(StoreApi.deleteOrder)
.addPUT(PetApi.updatePet)
.addPOST(PetApi.addPet)
.addGET(PetApi.findPetsByStatus)
.addGET(PetApi.findPetsByTags)
.addGET(PetApi.getPetById)
.addPOST(PetApi.updatePetWithForm)
.addDELETE(PetApi.deletePet)
.addPOST(PetApi.uploadFile)
;
// configures the app
swagger.configure("http://localhost:8002/v2", "0.1");
// start the server
app.listen(8002);

View File

@ -1,16 +1,15 @@
{ {
"name": "swagger-client", "name": "",
"description": "Wordnik node.js server generator", "version": "",
"version": "1.0.0", "description": "This is a sample server Petstore server. You can find out more about Swagger at &lt;a href=&quot;http://swagger.io&quot;&gt;http://swagger.io&lt;/a&gt; or on irc.freenode.net, #swagger. For this sample, you can use the api key &quot;special-key&quot; to test the authorization filters",
"homepage": "", "main": "index.js",
"main": "./main.js", "keywords": [
"engines": { "swagger"
"node": ">= 0.8.x" ],
}, "license": "MIT",
"private": true,
"dependencies": { "dependencies": {
"swagger-node-express": ">= 2.0.x", "connect": "^3.2.0",
"connect": ">= 1.8.x", "swagger-tools": "0.8.*"
"cors": "2.1.1",
"express": "3.x"
} }
} }