diff --git a/bin/nodejs-petstore-server.sh b/bin/nodejs-petstore-server.sh index 3fff1bdc0c0..2d9994f49e5 100755 --- a/bin/nodejs-petstore-server.sh +++ b/bin/nodejs-petstore-server.sh @@ -26,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l nodejs-server -o samples/server/petstore/nodejs" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/nodejs -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l nodejs-server -o samples/server/petstore/nodejs" java $JAVA_OPTS -Dservice -jar $executable $ags diff --git a/modules/swagger-codegen/XhhGitIgnore/sdk_unit_testing_binary.json b/modules/swagger-codegen/XhhGitIgnore/sdk_unit_testing_binary.json deleted file mode 100644 index 2d87e3bcb7f..00000000000 --- a/modules/swagger-codegen/XhhGitIgnore/sdk_unit_testing_binary.json +++ /dev/null @@ -1,67 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "version": "1.0.0", - "title": "SDK Unit Testing - File Downloading" - }, - "schemes": [ - "http" - ], - "host": "localhost:3000", - "basePath": "/unittesting", - "paths": { - "/request/file_uploading": { - "get": { - "operationId": "file_uploading", - "tags": [ - "Request" - ], - "parameters": [ - {"name": "f1", - "in": "formData", - "type": "string", - "format": "binary", - "required": true - }, - {"name": "f2", - "in": "formData", - "type": "string", - "format": "binary", - "required": false - } - ], - "consumes": [ - "multipart/form-data" - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "string" - } - } - } - } - }, - "/response/file_downloading": { - "get": { - "operationId": "file_downloading", - "tags": [ - "Response" - ], - "produces": [ - "multipart/form-data" - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "string", - "format": "binary" - } - } - } - } - } - } -} diff --git a/modules/swagger-codegen/XhhGitIgnore/sdk_unit_testing_file_downloading.json b/modules/swagger-codegen/XhhGitIgnore/sdk_unit_testing_file_downloading.json deleted file mode 100644 index 6169272c05d..00000000000 --- a/modules/swagger-codegen/XhhGitIgnore/sdk_unit_testing_file_downloading.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "version": "1.0.0", - "title": "SDK Unit Testing - File Downloading" - }, - "schemes": [ - "http" - ], - "host": "localhost:3000", - "basePath": "/unittesting", - "paths": { - "/response/file_downloading": { - "get": { - "operationId": "file_downloading", - "tags": [ - "Response" - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "file" - } - } - } - } - } - } -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java index 87e44d23632..56f17fbcfdc 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java @@ -19,11 +19,12 @@ import java.io.IOException; import java.math.BigDecimal; import java.util.*; import java.util.Map.Entry; +import java.util.regex.Pattern; public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(NodeJSServerCodegen.class); - + protected String implFolder = "service"; public static final String GOOGLE_CLOUD_FUNCTIONS = "googleCloudFunctions"; public static final String EXPORTED_NAME = "exportedName"; @@ -81,16 +82,19 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig */ additionalProperties.put("apiVersion", apiVersion); additionalProperties.put("serverPort", serverPort); + additionalProperties.put("implFolder", implFolder); + + supportingFiles.add(new SupportingFile("writer.mustache", ("utils").replace(".", "/"), "writer.js")); cliOptions.add(CliOption.newBoolean(GOOGLE_CLOUD_FUNCTIONS, - "When specified, it will generate the code which runs within Google Cloud Functions " - + "instead of standalone Node.JS server. See " - + "https://cloud.google.com/functions/docs/quickstart for the details of how to " - + "deploy the generated code.")); + "When specified, it will generate the code which runs within Google Cloud Functions " + + "instead of standalone Node.JS server. See " + + "https://cloud.google.com/functions/docs/quickstart for the details of how to " + + "deploy the generated code.")); cliOptions.add(new CliOption(EXPORTED_NAME, - "When the generated code will be deployed to Google Cloud Functions, this option can be " - + "used to update the name of the exported function. By default, it refers to the " - + "basePath. This does not affect normal standalone nodejs server code.")); + "When the generated code will be deployed to Google Cloud Functions, this option can be " + + "used to update the name of the exported function. By default, it refers to the " + + "basePath. This does not affect normal standalone nodejs server code.")); } @Override @@ -145,15 +149,35 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig return toApiName(name); } + + @Override + public String apiFilename(String templateName, String tag) { + String result = super.apiFilename(templateName, tag); + + if ( templateName.equals("service.mustache") ) { + String stringToMatch = File.separator + "controllers" + File.separator; + String replacement = File.separator + implFolder + File.separator; + result = result.replaceAll(Pattern.quote(stringToMatch), replacement); + } + return result; + } + + private String implFileFolder(String output) { + return outputFolder + "/" + output + "/" + apiPackage().replace('.', '/'); + } + /** * 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 + * those terms here. This logic is only called if a variable matches the reserved words * * @return the escaped term */ @Override public String escapeReservedWord(String name) { - return "_" + name; // add an underscore to the name + if(this.reservedWords().contains(name)) { + name = "_" + name; + } + return name; } /** @@ -256,7 +280,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig if (additionalProperties.containsKey(GOOGLE_CLOUD_FUNCTIONS)) { setGoogleCloudFunctions( - Boolean.valueOf(additionalProperties.get(GOOGLE_CLOUD_FUNCTIONS).toString())); + Boolean.valueOf(additionalProperties.get(GOOGLE_CLOUD_FUNCTIONS).toString())); } if (additionalProperties.containsKey(EXPORTED_NAME)) { @@ -273,8 +297,8 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig // "controller.js") // ); supportingFiles.add(new SupportingFile("swagger.mustache", - "api", - "swagger.yaml") + "api", + "swagger.yaml") ); if (getGoogleCloudFunctions()) { writeOptional(outputFolder, new SupportingFile("index-gcf.mustache", "", "index.js")); @@ -307,7 +331,12 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig if (info.getTitle() != null) { // when info.title is defined, use it for projectName // used in package.json - projectName = dashize(info.getTitle()); + projectName = info.getTitle() + .replaceAll("[^a-zA-Z0-9]", "-") + .replaceAll("^[-]*", "") + .replaceAll("[-]*$", "") + .replaceAll("[-]{2,}", "-") + .toLowerCase(); this.additionalProperties.put("projectName", projectName); } } @@ -318,14 +347,14 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig if (!host.endsWith(".cloudfunctions.net")) { LOGGER.warn("Host " + host + " seems not matching with cloudfunctions.net URL."); } - if (!additionalProperties.containsKey(EXPORTED_NAME)) { + if (!additionalProperties.containsKey(EXPORTED_NAME)) { String basePath = swagger.getBasePath(); if (basePath == null || basePath.equals("/")) { LOGGER.warn("Cannot find the exported name properly. Using 'openapi' as the exported name"); basePath = "/openapi"; } additionalProperties.put(EXPORTED_NAME, basePath.substring(1)); - } + } } // need vendor extensions for x-swagger-router-controller @@ -353,7 +382,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig } } - @Override + @Override public Map postProcessSupportingFileData(Map objs) { Swagger swagger = (Swagger)objs.get("swagger"); if(swagger != null) { @@ -362,7 +391,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig module.addSerializer(Double.class, new JsonSerializer() { @Override public void serialize(Double val, JsonGenerator jgen, - SerializerProvider provider) throws IOException, JsonProcessingException { + SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeNumber(new BigDecimal(val)); } }); diff --git a/modules/swagger-codegen/src/main/resources/nodejs/controller.mustache b/modules/swagger-codegen/src/main/resources/nodejs/controller.mustache index f94fe89ef7e..69ff7249f9d 100644 --- a/modules/swagger-codegen/src/main/resources/nodejs/controller.mustache +++ b/modules/swagger-codegen/src/main/resources/nodejs/controller.mustache @@ -1,13 +1,21 @@ 'use strict'; -var url = require('url'); +var utils = require('../utils/writer.js'); {{#operations}} - -var {{classname}} = require('./{{classname}}Service'); +var {{classname}} = require('../{{implFolder}}/{{classname}}Service'); {{#operation}} module.exports.{{nickname}} = function {{nickname}} (req, res, next) { - {{classname}}.{{nickname}}(req.swagger.params, res, next); + {{#allParams}} + var {{paramName}} = req.swagger.params['{{baseName}}'].value; + {{/allParams}} + {{classname}}.{{nickname}}({{#allParams}}{{paramName}}{{#hasMore}},{{/hasMore}}{{/allParams}}) + .then(function (response) { + utils.writeJson(res, response); + }) + .catch(function (response) { + utils.writeJson(res, response); + }); }; {{/operation}} {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/nodejs/service.mustache b/modules/swagger-codegen/src/main/resources/nodejs/service.mustache index e5a44836e07..90d354b1a14 100644 --- a/modules/swagger-codegen/src/main/resources/nodejs/service.mustache +++ b/modules/swagger-codegen/src/main/resources/nodejs/service.mustache @@ -2,40 +2,42 @@ {{#operations}} {{#operation}} -exports.{{{operationId}}} = function(args, res, next) { - /** - {{#summary}} - * {{{summary}}} - {{/summary}} - {{#notes}} - * {{{notes}}} - {{/notes}} - * - {{#allParams}} - * {{paramName}} {{{dataType}}} {{{description}}}{{^required}} (optional){{/required}} - {{/allParams}} - {{^returnType}} - * no response value expected for this operation - {{/returnType}} + +/** + {{#summary}} + * {{{summary}}} + {{/summary}} + {{#notes}} + * {{{notes}}} + {{/notes}} + * +{{#allParams}} + * {{paramName}} {{{dataType}}} {{{description}}}{{^required}} (optional){{/required}} +{{/allParams}} +{{^returnType}} + * no response value expected for this operation +{{/returnType}} +{{#returnType}} + * returns {{{returnType}}} +{{/returnType}} + **/ +exports.{{{operationId}}} = function({{#allParams}}{{paramName}}{{#hasMore}},{{/hasMore}}{{/allParams}}) { + return new Promise(function(resolve, reject) { {{#returnType}} - * returns {{{returnType}}} - {{/returnType}} - **/ - {{#returnType}} - var examples = {}; - {{#examples}} - examples['{{contentType}}'] = {{{example}}}; - {{/examples}} - if (Object.keys(examples).length > 0) { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); - } else { - res.end(); - } - {{/returnType}} - {{^returnType}} - res.end(); - {{/returnType}} + var examples = {}; + {{#examples}} + examples['{{contentType}}'] = {{{example}}}; + {{/examples}} + if (Object.keys(examples).length > 0) { + resolve(examples[Object.keys(examples)[0]]); + } else { + resolve(); + } + {{/returnType}} + {{^returnType}} + resolve(); + {{/returnType}} + }); } {{/operation}} diff --git a/modules/swagger-codegen/src/main/resources/nodejs/writer.mustache b/modules/swagger-codegen/src/main/resources/nodejs/writer.mustache new file mode 100644 index 00000000000..7350b54371f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/nodejs/writer.mustache @@ -0,0 +1,43 @@ +var ResponsePayload = function(code, payload) { + this.code = code; + this.payload = payload; +} + +exports.respondWithCode = function(code, payload) { + return new ResponsePayload(code, payload); +} + +var writeJson = exports.writeJson = function(response, arg1, arg2) { + var code; + var payload; + + if(arg1 && arg1 instanceof ResponsePayload) { + writeJson(response, arg1.payload, arg1.code); + return; + } + + if(arg2 && Number.isInteger(arg2)) { + code = arg2; + } + else { + if(arg1 && Number.isInteger(arg1)) { + code = arg1; + } + } + if(code && arg1) { + payload = arg1; + } + else if(arg1) { + payload = arg1; + } + + if(!code) { + // if no response code given, we default to 200 + code = 200; + } + if(typeof payload === 'object') { + payload = JSON.stringify(payload, null, 2); + } + response.writeHead(code, {'Content-Type': 'application/json'}); + response.end(payload, code); +} \ No newline at end of file diff --git a/samples/server/petstore/nodejs/controllers/Pet.js b/samples/server/petstore/nodejs/controllers/Pet.js index 5ff24c0591f..da34222e952 100644 --- a/samples/server/petstore/nodejs/controllers/Pet.js +++ b/samples/server/petstore/nodejs/controllers/Pet.js @@ -1,37 +1,97 @@ 'use strict'; -var url = require('url'); - -var Pet = require('./PetService'); +var utils = require('../utils/writer.js'); +var Pet = require('../service/PetService'); module.exports.addPet = function addPet (req, res, next) { - Pet.addPet(req.swagger.params, res, next); + var body = req.swagger.params['body'].value; + Pet.addPet(body) + .then(function (response) { + utils.writeJson(res, response); + }) + .catch(function (response) { + utils.writeJson(res, response); + }); }; module.exports.deletePet = function deletePet (req, res, next) { - Pet.deletePet(req.swagger.params, res, next); + var petId = req.swagger.params['petId'].value; + var api_key = req.swagger.params['api_key'].value; + Pet.deletePet(petId,api_key) + .then(function (response) { + utils.writeJson(res, response); + }) + .catch(function (response) { + utils.writeJson(res, response); + }); }; module.exports.findPetsByStatus = function findPetsByStatus (req, res, next) { - Pet.findPetsByStatus(req.swagger.params, res, next); + var status = req.swagger.params['status'].value; + Pet.findPetsByStatus(status) + .then(function (response) { + utils.writeJson(res, response); + }) + .catch(function (response) { + utils.writeJson(res, response); + }); }; module.exports.findPetsByTags = function findPetsByTags (req, res, next) { - Pet.findPetsByTags(req.swagger.params, res, next); + var tags = req.swagger.params['tags'].value; + Pet.findPetsByTags(tags) + .then(function (response) { + utils.writeJson(res, response); + }) + .catch(function (response) { + utils.writeJson(res, response); + }); }; module.exports.getPetById = function getPetById (req, res, next) { - Pet.getPetById(req.swagger.params, res, next); + var petId = req.swagger.params['petId'].value; + Pet.getPetById(petId) + .then(function (response) { + utils.writeJson(res, response); + }) + .catch(function (response) { + utils.writeJson(res, response); + }); }; module.exports.updatePet = function updatePet (req, res, next) { - Pet.updatePet(req.swagger.params, res, next); + var body = req.swagger.params['body'].value; + Pet.updatePet(body) + .then(function (response) { + utils.writeJson(res, response); + }) + .catch(function (response) { + utils.writeJson(res, response); + }); }; module.exports.updatePetWithForm = function updatePetWithForm (req, res, next) { - Pet.updatePetWithForm(req.swagger.params, res, next); + var petId = req.swagger.params['petId'].value; + var name = req.swagger.params['name'].value; + var status = req.swagger.params['status'].value; + Pet.updatePetWithForm(petId,name,status) + .then(function (response) { + utils.writeJson(res, response); + }) + .catch(function (response) { + utils.writeJson(res, response); + }); }; module.exports.uploadFile = function uploadFile (req, res, next) { - Pet.uploadFile(req.swagger.params, res, next); + var petId = req.swagger.params['petId'].value; + var additionalMetadata = req.swagger.params['additionalMetadata'].value; + var file = req.swagger.params['file'].value; + Pet.uploadFile(petId,additionalMetadata,file) + .then(function (response) { + utils.writeJson(res, response); + }) + .catch(function (response) { + utils.writeJson(res, response); + }); }; diff --git a/samples/server/petstore/nodejs/controllers/PetService.js b/samples/server/petstore/nodejs/controllers/PetService.js deleted file mode 100644 index 8a4235a35fc..00000000000 --- a/samples/server/petstore/nodejs/controllers/PetService.js +++ /dev/null @@ -1,166 +0,0 @@ -'use strict'; - -exports.addPet = function(args, res, next) { - /** - * Add a new pet to the store - * - * - * body Pet Pet object that needs to be added to the store - * no response value expected for this operation - **/ - res.end(); -} - -exports.deletePet = function(args, res, next) { - /** - * Deletes a pet - * - * - * petId Long Pet id to delete - * api_key String (optional) - * no response value expected for this operation - **/ - res.end(); -} - -exports.findPetsByStatus = function(args, res, next) { - /** - * Finds Pets by status - * Multiple status values can be provided with comma separated strings - * - * status List Status values that need to be considered for filter - * returns List - **/ - var examples = {}; - examples['application/json'] = [ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], - "id" : 123456789, - "category" : { - "id" : 123456789, - "name" : "aeiou" - }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ]; - if (Object.keys(examples).length > 0) { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); - } else { - res.end(); - } -} - -exports.findPetsByTags = function(args, res, next) { - /** - * Finds Pets by tags - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * - * tags List Tags to filter by - * returns List - **/ - var examples = {}; - examples['application/json'] = [ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], - "id" : 123456789, - "category" : { - "id" : 123456789, - "name" : "aeiou" - }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ]; - if (Object.keys(examples).length > 0) { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); - } else { - res.end(); - } -} - -exports.getPetById = function(args, res, next) { - /** - * Find pet by ID - * Returns a single pet - * - * petId Long ID of pet to return - * returns Pet - **/ - var examples = {}; - examples['application/json'] = { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], - "id" : 123456789, - "category" : { - "id" : 123456789, - "name" : "aeiou" - }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -}; - if (Object.keys(examples).length > 0) { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); - } else { - res.end(); - } -} - -exports.updatePet = function(args, res, next) { - /** - * Update an existing pet - * - * - * body Pet Pet object that needs to be added to the store - * no response value expected for this operation - **/ - res.end(); -} - -exports.updatePetWithForm = function(args, res, next) { - /** - * Updates a pet in the store with form data - * - * - * petId Long ID of pet that needs to be updated - * name String Updated name of the pet (optional) - * status String Updated status of the pet (optional) - * no response value expected for this operation - **/ - res.end(); -} - -exports.uploadFile = function(args, res, next) { - /** - * uploads an image - * - * - * petId Long ID of pet to update - * additionalMetadata String Additional data to pass to server (optional) - * file File file to upload (optional) - * returns ApiResponse - **/ - var examples = {}; - examples['application/json'] = { - "message" : "aeiou", - "code" : 123, - "type" : "aeiou" -}; - if (Object.keys(examples).length > 0) { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); - } else { - res.end(); - } -} - diff --git a/samples/server/petstore/nodejs/controllers/Store.js b/samples/server/petstore/nodejs/controllers/Store.js index 94d86b7b590..b781e64556f 100644 --- a/samples/server/petstore/nodejs/controllers/Store.js +++ b/samples/server/petstore/nodejs/controllers/Store.js @@ -1,21 +1,47 @@ 'use strict'; -var url = require('url'); - -var Store = require('./StoreService'); +var utils = require('../utils/writer.js'); +var Store = require('../service/StoreService'); module.exports.deleteOrder = function deleteOrder (req, res, next) { - Store.deleteOrder(req.swagger.params, res, next); + var orderId = req.swagger.params['orderId'].value; + Store.deleteOrder(orderId) + .then(function (response) { + utils.writeJson(res, response); + }) + .catch(function (response) { + utils.writeJson(res, response); + }); }; module.exports.getInventory = function getInventory (req, res, next) { - Store.getInventory(req.swagger.params, res, next); + Store.getInventory() + .then(function (response) { + utils.writeJson(res, response); + }) + .catch(function (response) { + utils.writeJson(res, response); + }); }; module.exports.getOrderById = function getOrderById (req, res, next) { - Store.getOrderById(req.swagger.params, res, next); + var orderId = req.swagger.params['orderId'].value; + Store.getOrderById(orderId) + .then(function (response) { + utils.writeJson(res, response); + }) + .catch(function (response) { + utils.writeJson(res, response); + }); }; module.exports.placeOrder = function placeOrder (req, res, next) { - Store.placeOrder(req.swagger.params, res, next); + var body = req.swagger.params['body'].value; + Store.placeOrder(body) + .then(function (response) { + utils.writeJson(res, response); + }) + .catch(function (response) { + utils.writeJson(res, response); + }); }; diff --git a/samples/server/petstore/nodejs/controllers/StoreService.js b/samples/server/petstore/nodejs/controllers/StoreService.js deleted file mode 100644 index 7da8e0ceb23..00000000000 --- a/samples/server/petstore/nodejs/controllers/StoreService.js +++ /dev/null @@ -1,82 +0,0 @@ -'use strict'; - -exports.deleteOrder = function(args, res, next) { - /** - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * - * orderId String ID of the order that needs to be deleted - * no response value expected for this operation - **/ - res.end(); -} - -exports.getInventory = function(args, res, next) { - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * - * returns Map - **/ - var examples = {}; - examples['application/json'] = { - "key" : 123 -}; - if (Object.keys(examples).length > 0) { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); - } else { - res.end(); - } -} - -exports.getOrderById = function(args, res, next) { - /** - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * - * orderId Long ID of pet that needs to be fetched - * returns Order - **/ - var examples = {}; - examples['application/json'] = { - "id" : 123456789, - "petId" : 123456789, - "complete" : true, - "status" : "aeiou", - "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}; - if (Object.keys(examples).length > 0) { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); - } else { - res.end(); - } -} - -exports.placeOrder = function(args, res, next) { - /** - * Place an order for a pet - * - * - * body Order order placed for purchasing the pet - * returns Order - **/ - var examples = {}; - examples['application/json'] = { - "id" : 123456789, - "petId" : 123456789, - "complete" : true, - "status" : "aeiou", - "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}; - if (Object.keys(examples).length > 0) { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); - } else { - res.end(); - } -} - diff --git a/samples/server/petstore/nodejs/controllers/User.js b/samples/server/petstore/nodejs/controllers/User.js index 4b118e8211d..f444efa38e5 100644 --- a/samples/server/petstore/nodejs/controllers/User.js +++ b/samples/server/petstore/nodejs/controllers/User.js @@ -1,37 +1,93 @@ 'use strict'; -var url = require('url'); - -var User = require('./UserService'); +var utils = require('../utils/writer.js'); +var User = require('../service/UserService'); module.exports.createUser = function createUser (req, res, next) { - User.createUser(req.swagger.params, res, next); + var body = req.swagger.params['body'].value; + User.createUser(body) + .then(function (response) { + utils.writeJson(res, response); + }) + .catch(function (response) { + utils.writeJson(res, response); + }); }; module.exports.createUsersWithArrayInput = function createUsersWithArrayInput (req, res, next) { - User.createUsersWithArrayInput(req.swagger.params, res, next); + var body = req.swagger.params['body'].value; + User.createUsersWithArrayInput(body) + .then(function (response) { + utils.writeJson(res, response); + }) + .catch(function (response) { + utils.writeJson(res, response); + }); }; module.exports.createUsersWithListInput = function createUsersWithListInput (req, res, next) { - User.createUsersWithListInput(req.swagger.params, res, next); + var body = req.swagger.params['body'].value; + User.createUsersWithListInput(body) + .then(function (response) { + utils.writeJson(res, response); + }) + .catch(function (response) { + utils.writeJson(res, response); + }); }; module.exports.deleteUser = function deleteUser (req, res, next) { - User.deleteUser(req.swagger.params, res, next); + var username = req.swagger.params['username'].value; + User.deleteUser(username) + .then(function (response) { + utils.writeJson(res, response); + }) + .catch(function (response) { + utils.writeJson(res, response); + }); }; module.exports.getUserByName = function getUserByName (req, res, next) { - User.getUserByName(req.swagger.params, res, next); + var username = req.swagger.params['username'].value; + User.getUserByName(username) + .then(function (response) { + utils.writeJson(res, response); + }) + .catch(function (response) { + utils.writeJson(res, response); + }); }; module.exports.loginUser = function loginUser (req, res, next) { - User.loginUser(req.swagger.params, res, next); + var username = req.swagger.params['username'].value; + var password = req.swagger.params['password'].value; + User.loginUser(username,password) + .then(function (response) { + utils.writeJson(res, response); + }) + .catch(function (response) { + utils.writeJson(res, response); + }); }; module.exports.logoutUser = function logoutUser (req, res, next) { - User.logoutUser(req.swagger.params, res, next); + User.logoutUser() + .then(function (response) { + utils.writeJson(res, response); + }) + .catch(function (response) { + utils.writeJson(res, response); + }); }; module.exports.updateUser = function updateUser (req, res, next) { - User.updateUser(req.swagger.params, res, next); + var username = req.swagger.params['username'].value; + var body = req.swagger.params['body'].value; + User.updateUser(username,body) + .then(function (response) { + utils.writeJson(res, response); + }) + .catch(function (response) { + utils.writeJson(res, response); + }); }; diff --git a/samples/server/petstore/nodejs/controllers/UserService.js b/samples/server/petstore/nodejs/controllers/UserService.js deleted file mode 100644 index 99090323f78..00000000000 --- a/samples/server/petstore/nodejs/controllers/UserService.js +++ /dev/null @@ -1,114 +0,0 @@ -'use strict'; - -exports.createUser = function(args, res, next) { - /** - * Create user - * This can only be done by the logged in user. - * - * body User Created user object - * no response value expected for this operation - **/ - res.end(); -} - -exports.createUsersWithArrayInput = function(args, res, next) { - /** - * Creates list of users with given input array - * - * - * body List List of user object - * no response value expected for this operation - **/ - res.end(); -} - -exports.createUsersWithListInput = function(args, res, next) { - /** - * Creates list of users with given input array - * - * - * body List List of user object - * no response value expected for this operation - **/ - res.end(); -} - -exports.deleteUser = function(args, res, next) { - /** - * Delete user - * This can only be done by the logged in user. - * - * username String The name that needs to be deleted - * no response value expected for this operation - **/ - res.end(); -} - -exports.getUserByName = function(args, res, next) { - /** - * Get user by user name - * - * - * username String The name that needs to be fetched. Use user1 for testing. - * returns User - **/ - var examples = {}; - examples['application/json'] = { - "id" : 123456789, - "lastName" : "aeiou", - "phone" : "aeiou", - "username" : "aeiou", - "email" : "aeiou", - "userStatus" : 123, - "firstName" : "aeiou", - "password" : "aeiou" -}; - if (Object.keys(examples).length > 0) { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); - } else { - res.end(); - } -} - -exports.loginUser = function(args, res, next) { - /** - * Logs user into the system - * - * - * username String The user name for login - * password String The password for login in clear text - * returns String - **/ - var examples = {}; - examples['application/json'] = "aeiou"; - if (Object.keys(examples).length > 0) { - res.setHeader('Content-Type', 'application/json'); - res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); - } else { - res.end(); - } -} - -exports.logoutUser = function(args, res, next) { - /** - * Logs out current logged in user session - * - * - * no response value expected for this operation - **/ - res.end(); -} - -exports.updateUser = function(args, res, next) { - /** - * Updated user - * This can only be done by the logged in user. - * - * username String name that need to be deleted - * body User Updated user object - * no response value expected for this operation - **/ - res.end(); -} - diff --git a/samples/server/petstore/nodejs/service/PetService.js b/samples/server/petstore/nodejs/service/PetService.js new file mode 100644 index 00000000000..b875a7d83b1 --- /dev/null +++ b/samples/server/petstore/nodejs/service/PetService.js @@ -0,0 +1,186 @@ +'use strict'; + + +/** + * Add a new pet to the store + * + * + * body Pet Pet object that needs to be added to the store + * no response value expected for this operation + **/ +exports.addPet = function(body) { + return new Promise(function(resolve, reject) { + resolve(); + }); +} + + +/** + * Deletes a pet + * + * + * petId Long Pet id to delete + * api_key String (optional) + * no response value expected for this operation + **/ +exports.deletePet = function(petId,api_key) { + return new Promise(function(resolve, reject) { + resolve(); + }); +} + + +/** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * + * status List Status values that need to be considered for filter + * returns List + **/ +exports.findPetsByStatus = function(status) { + return new Promise(function(resolve, reject) { + var examples = {}; + examples['application/json'] = [ { + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], + "id" : 123456789, + "category" : { + "id" : 123456789, + "name" : "aeiou" + }, + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] +} ]; + if (Object.keys(examples).length > 0) { + resolve(examples[Object.keys(examples)[0]]); + } else { + resolve(); + } + }); +} + + +/** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + * tags List Tags to filter by + * returns List + **/ +exports.findPetsByTags = function(tags) { + return new Promise(function(resolve, reject) { + var examples = {}; + examples['application/json'] = [ { + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], + "id" : 123456789, + "category" : { + "id" : 123456789, + "name" : "aeiou" + }, + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] +} ]; + if (Object.keys(examples).length > 0) { + resolve(examples[Object.keys(examples)[0]]); + } else { + resolve(); + } + }); +} + + +/** + * Find pet by ID + * Returns a single pet + * + * petId Long ID of pet to return + * returns Pet + **/ +exports.getPetById = function(petId) { + return new Promise(function(resolve, reject) { + var examples = {}; + examples['application/json'] = { + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], + "id" : 123456789, + "category" : { + "id" : 123456789, + "name" : "aeiou" + }, + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] +}; + if (Object.keys(examples).length > 0) { + resolve(examples[Object.keys(examples)[0]]); + } else { + resolve(); + } + }); +} + + +/** + * Update an existing pet + * + * + * body Pet Pet object that needs to be added to the store + * no response value expected for this operation + **/ +exports.updatePet = function(body) { + return new Promise(function(resolve, reject) { + resolve(); + }); +} + + +/** + * Updates a pet in the store with form data + * + * + * petId Long ID of pet that needs to be updated + * name String Updated name of the pet (optional) + * status String Updated status of the pet (optional) + * no response value expected for this operation + **/ +exports.updatePetWithForm = function(petId,name,status) { + return new Promise(function(resolve, reject) { + resolve(); + }); +} + + +/** + * uploads an image + * + * + * petId Long ID of pet to update + * additionalMetadata String Additional data to pass to server (optional) + * file File file to upload (optional) + * returns ApiResponse + **/ +exports.uploadFile = function(petId,additionalMetadata,file) { + return new Promise(function(resolve, reject) { + var examples = {}; + examples['application/json'] = { + "message" : "aeiou", + "code" : 123, + "type" : "aeiou" +}; + if (Object.keys(examples).length > 0) { + resolve(examples[Object.keys(examples)[0]]); + } else { + resolve(); + } + }); +} + diff --git a/samples/server/petstore/nodejs/service/StoreService.js b/samples/server/petstore/nodejs/service/StoreService.js new file mode 100644 index 00000000000..3bdcae7ad80 --- /dev/null +++ b/samples/server/petstore/nodejs/service/StoreService.js @@ -0,0 +1,91 @@ +'use strict'; + + +/** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + * orderId String ID of the order that needs to be deleted + * no response value expected for this operation + **/ +exports.deleteOrder = function(orderId) { + return new Promise(function(resolve, reject) { + resolve(); + }); +} + + +/** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * + * returns Map + **/ +exports.getInventory = function() { + return new Promise(function(resolve, reject) { + var examples = {}; + examples['application/json'] = { + "key" : 123 +}; + if (Object.keys(examples).length > 0) { + resolve(examples[Object.keys(examples)[0]]); + } else { + resolve(); + } + }); +} + + +/** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + * orderId Long ID of pet that needs to be fetched + * returns Order + **/ +exports.getOrderById = function(orderId) { + return new Promise(function(resolve, reject) { + var examples = {}; + examples['application/json'] = { + "id" : 123456789, + "petId" : 123456789, + "complete" : true, + "status" : "aeiou", + "quantity" : 123, + "shipDate" : "2000-01-23T04:56:07.000+00:00" +}; + if (Object.keys(examples).length > 0) { + resolve(examples[Object.keys(examples)[0]]); + } else { + resolve(); + } + }); +} + + +/** + * Place an order for a pet + * + * + * body Order order placed for purchasing the pet + * returns Order + **/ +exports.placeOrder = function(body) { + return new Promise(function(resolve, reject) { + var examples = {}; + examples['application/json'] = { + "id" : 123456789, + "petId" : 123456789, + "complete" : true, + "status" : "aeiou", + "quantity" : 123, + "shipDate" : "2000-01-23T04:56:07.000+00:00" +}; + if (Object.keys(examples).length > 0) { + resolve(examples[Object.keys(examples)[0]]); + } else { + resolve(); + } + }); +} + diff --git a/samples/server/petstore/nodejs/service/UserService.js b/samples/server/petstore/nodejs/service/UserService.js new file mode 100644 index 00000000000..6b15ac09636 --- /dev/null +++ b/samples/server/petstore/nodejs/service/UserService.js @@ -0,0 +1,136 @@ +'use strict'; + + +/** + * Create user + * This can only be done by the logged in user. + * + * body User Created user object + * no response value expected for this operation + **/ +exports.createUser = function(body) { + return new Promise(function(resolve, reject) { + resolve(); + }); +} + + +/** + * Creates list of users with given input array + * + * + * body List List of user object + * no response value expected for this operation + **/ +exports.createUsersWithArrayInput = function(body) { + return new Promise(function(resolve, reject) { + resolve(); + }); +} + + +/** + * Creates list of users with given input array + * + * + * body List List of user object + * no response value expected for this operation + **/ +exports.createUsersWithListInput = function(body) { + return new Promise(function(resolve, reject) { + resolve(); + }); +} + + +/** + * Delete user + * This can only be done by the logged in user. + * + * username String The name that needs to be deleted + * no response value expected for this operation + **/ +exports.deleteUser = function(username) { + return new Promise(function(resolve, reject) { + resolve(); + }); +} + + +/** + * Get user by user name + * + * + * username String The name that needs to be fetched. Use user1 for testing. + * returns User + **/ +exports.getUserByName = function(username) { + return new Promise(function(resolve, reject) { + var examples = {}; + examples['application/json'] = { + "id" : 123456789, + "lastName" : "aeiou", + "phone" : "aeiou", + "username" : "aeiou", + "email" : "aeiou", + "userStatus" : 123, + "firstName" : "aeiou", + "password" : "aeiou" +}; + if (Object.keys(examples).length > 0) { + resolve(examples[Object.keys(examples)[0]]); + } else { + resolve(); + } + }); +} + + +/** + * Logs user into the system + * + * + * username String The user name for login + * password String The password for login in clear text + * returns String + **/ +exports.loginUser = function(username,password) { + return new Promise(function(resolve, reject) { + var examples = {}; + examples['application/json'] = "aeiou"; + if (Object.keys(examples).length > 0) { + resolve(examples[Object.keys(examples)[0]]); + } else { + resolve(); + } + }); +} + + +/** + * Logs out current logged in user session + * + * + * no response value expected for this operation + **/ +exports.logoutUser = function() { + return new Promise(function(resolve, reject) { + resolve(); + }); +} + + +/** + * Updated user + * This can only be done by the logged in user. + * + * username String name that need to be deleted + * body User Updated user object + * no response value expected for this operation + **/ +exports.updateUser = function(username,body) { + return new Promise(function(resolve, reject) { + resolve(); + }); +} + diff --git a/samples/server/petstore/nodejs/utils/writer.js b/samples/server/petstore/nodejs/utils/writer.js new file mode 100644 index 00000000000..7350b54371f --- /dev/null +++ b/samples/server/petstore/nodejs/utils/writer.js @@ -0,0 +1,43 @@ +var ResponsePayload = function(code, payload) { + this.code = code; + this.payload = payload; +} + +exports.respondWithCode = function(code, payload) { + return new ResponsePayload(code, payload); +} + +var writeJson = exports.writeJson = function(response, arg1, arg2) { + var code; + var payload; + + if(arg1 && arg1 instanceof ResponsePayload) { + writeJson(response, arg1.payload, arg1.code); + return; + } + + if(arg2 && Number.isInteger(arg2)) { + code = arg2; + } + else { + if(arg1 && Number.isInteger(arg1)) { + code = arg1; + } + } + if(code && arg1) { + payload = arg1; + } + else if(arg1) { + payload = arg1; + } + + if(!code) { + // if no response code given, we default to 200 + code = 200; + } + if(typeof payload === 'object') { + payload = JSON.stringify(payload, null, 2); + } + response.writeHead(code, {'Content-Type': 'application/json'}); + response.end(payload, code); +} \ No newline at end of file