Compare commits

...

3 Commits

Author SHA1 Message Date
William Cheng
605030dfeb add windows batch file 2019-04-01 22:56:57 +08:00
William Cheng
ecb11fbe7f remove unused files 2019-04-01 22:54:02 +08:00
William Cheng
5cd3a16e56 add nodejs fastify server generator 2019-04-01 22:53:07 +08:00
18 changed files with 1931 additions and 0 deletions

View File

@ -0,0 +1,32 @@
#!/bin/sh
SCRIPT="$0"
echo "# START SCRIPT: $SCRIPT"
while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done
if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi
executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar"
if [ ! -f "$executable" ]
then
mvn -B clean package
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 -t modules/openapi-generator/src/main/resources/nodejs-fastify-server -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g nodejs-fastify-server -o samples/server/petstore/nodejs-fastify-server $@"
java $JAVA_OPTS -jar $executable $ags

View File

@ -0,0 +1,10 @@
set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar
If Not Exist %executable% (
mvn clean package
)
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
set ags=generate -t modules\openapi-generator\src\main\resources\nodejs-fastify-server -i modules\openapi-generator\src\test\resources\2_0\petstore.yaml -g nodejs-fastify-server -o samples\server\petstore\nodejs-fastify-server
java %JAVA_OPTS% -jar %executable% %ags%

View File

@ -0,0 +1,153 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.languages;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import org.openapitools.codegen.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
public class NodeJSFastifyServerCodegen extends DefaultCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(NodeJSServerCodegen.class);
protected String projectName = "openapi-server";
public NodeJSFastifyServerCodegen() {
super();
outputFolder = "generated-code/nodejs-fastify";
modelTemplateFiles.clear();
apiTemplateFiles.clear();
embeddedTemplateDir = templateDir = "nodejs-fastify";
setReservedWordsLowerCase(
Arrays.asList(
"break", "case", "class", "catch", "const", "continue", "debugger",
"default", "delete", "do", "else", "export", "extends", "finally",
"for", "function", "if", "import", "in", "instanceof", "let", "new",
"return", "super", "switch", "this", "throw", "try", "typeof", "var",
"void", "while", "with", "yield")
);
supportingFiles.add(new SupportingFile("index.mustache", "", "index.js"));
supportingFiles.add(new SupportingFile("readme.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("openapi.mustache", "", "openapi.json"));
supportingFiles.add(new SupportingFile("package.mustache", "", "package.json"));
}
/**
* Configures the type of generator.
*
* @return the CodegenType for this generator
* @see org.openapitools.codegen.CodegenType
*/
@Override
public CodegenType getTag() {
return CodegenType.SERVER;
}
/**
* Configures a friendly name for the generator. This will be used by the generator
* to select the library with the -g flag.
*
* @return the friendly name for the generator
*/
@Override
public String getName() {
return "nodejs-fastify-server";
}
/**
* Returns human-friendly help for the generator. Provide the consumer with help
* tips, parameters here
*
* @return A string value for the help message
*/
@Override
public String getHelp() {
return "Generates a NodeJS Fastify server library";
}
@Override
public void processOpts() {
super.processOpts();
writeOptional(outputFolder, new SupportingFile("service.mustache", "", "service.js"));
}
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
generateJSONSpecFile(objs);
return super.postProcessSupportingFileData(objs);
}
@Override
public void preprocessOpenAPI(OpenAPI openAPI) {
if (openAPI.getInfo() != null) {
Info info = openAPI.getInfo();
if (info.getTitle() != null) {
// when info.title is defined, use it for projectName
// used in package.json
projectName = info.getTitle()
.replaceAll("[^a-zA-Z0-9]", "-")
.replaceAll("^[-]*", "")
.replaceAll("[-]*$", "")
.replaceAll("[-]{2,}", "-")
.toLowerCase(Locale.ROOT);
}
}
this.additionalProperties.put("projectName", projectName);
}
/**
* 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 reserved words
*
* @return the escaped term
*/
@Override
public String escapeReservedWord(String name) {
if (this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
}

View File

@ -61,6 +61,7 @@ org.openapitools.codegen.languages.JMeterClientCodegen
org.openapitools.codegen.languages.LuaClientCodegen
org.openapitools.codegen.languages.MysqlSchemaCodegen
org.openapitools.codegen.languages.NodeJSServerCodegen
org.openapitools.codegen.languages.NodeJSFastifyServerCodegen
org.openapitools.codegen.languages.ObjcClientCodegen
org.openapitools.codegen.languages.OpenAPIGenerator
org.openapitools.codegen.languages.OpenAPIYamlGenerator

View File

@ -0,0 +1,15 @@
# {{^projectName}}NodeJS Fastify Server{{/projectName}}{{{projectName}}}
## OpenAPI
- [openapi.json](openapi.json)
## Usage
In this directory use:
+ "npm install" to install its dependencies
+ "npm start" to start fastify using fastify-cli
+ "npm run dev" to start fastify using fastify-cli with logging to the console
+ "npm test" to run tests

View File

@ -0,0 +1,21 @@
'use strict';
var utils = require('../utils/writer.js');
{{#operations}}
var {{classname}} = require('../{{implFolder}}/{{classname}}Service');
{{#operation}}
module.exports.{{nickname}} = function {{nickname}} (req, 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}}

View File

@ -0,0 +1,44 @@
'use strict';
var swaggerTools = require('swagger-tools');
var jsyaml = require('js-yaml');
var fs = require('fs');
// swaggerRouter configuration
var options = {
controllers: './controllers',
useStubs: false
};
// The Swagger document (require it, build it programmatically, fetch it from a URL, ...)
var spec = fs.readFileSync('./api/openapi.yaml', 'utf8');
var swaggerDoc = jsyaml.safeLoad(spec);
function toPromise(f, req, res) {
return new Promise(function(resolve, reject) {
f(req, res, function(err) {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
exports.{{exportedName}} = function(req, res) {
swaggerTools.initializeMiddleware(swaggerDoc, function(middleware) {
var metadata = middleware.swaggerMetadata();
var validator = middleware.swaggerValidator();
var router = middleware.swaggerRouter(options);
req.url = swaggerDoc.basePath + req.url;
toPromise(metadata, req, res).then(function() {
return toPromise(validator, req, res);
}).then(function() {
return toPromise(router, req, res);
}).catch(function(err) {
console.error(err);
res.status(res.statusCode || 400).send(err);
});
});
};

View File

@ -0,0 +1,10 @@
const openapiGlue = require("../../index.js");
const options = {
specification: `${__dirname}/openapi.json`,
service: `${__dirname}/service.js`
};
module.exports = async function(fastify, opts) {
fastify.register(openapiGlue, options);
};

View File

@ -0,0 +1 @@
{{{openapi-json}}}

View File

@ -0,0 +1,25 @@
{
"name": "{{projectName}}",
"version": "{{appVersion}}",
"description": "{{{appDescription}}}",
"scripts": {
"start": "fastify start index.js",
"test": "tap test/test-*.js",
"dev": "fastify start -l info -P index.js"
},
"directories": {
"test": "test"
},
"keywords": [
"openapi", "openapi-generator"
],
"license": "Unlicense",
"dependencies": {
"fastify-plugin": "^1.0.1"
},
"devDependencies": {
"fastify": "^2.0.0",
"fastify-cli": "^1.0.0",
"tap": "^12.5.3"
}
}

View File

@ -0,0 +1,50 @@
class Service {
constructor() {}
{{#apiInfo}}
{{#apis}}
{{#operations}}
{{#operation}}
/**
{{#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}}
**/
async {{{operationId}}}(req, resp) {
console.log("{{{operationId}}}");
// TODO implement this endpoint
{{#returnType}}
{{#examples}}
/*return {{{example}}};
*/
{{/examples}}
return {};
{{/returnType}}
{{^returnType}}
return;
{{/returnType}}
};
}
{{/operation}}
{{/operations}}
{{/apis}}
{{/apiInfo}}
module.exports = config => new Service();

View File

@ -0,0 +1,23 @@
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator
# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md

View File

@ -0,0 +1 @@
4.0.0-SNAPSHOT

View File

@ -0,0 +1,15 @@
# openapi-petstore
## OpenAPI
- [openapi.json](openapi.json)
## Usage
In this directory use:
+ "npm install" to install its dependencies
+ "npm start" to start fastify using fastify-cli
+ "npm run dev" to start fastify using fastify-cli with logging to the console
+ "npm test" to run tests

View File

@ -0,0 +1,10 @@
const openapiGlue = require("../../index.js");
const options = {
specification: `${__dirname}/openapi.json`,
service: `${__dirname}/service.js`
};
module.exports = async function(fastify, opts) {
fastify.register(openapiGlue, options);
};

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,25 @@
{
"name": "openapi-petstore",
"version": "1.0.0",
"description": "This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.",
"scripts": {
"start": "fastify start index.js",
"test": "tap test/test-*.js",
"dev": "fastify start -l info -P index.js"
},
"directories": {
"test": "test"
},
"keywords": [
"openapi", "openapi-generator"
],
"license": "Unlicense",
"dependencies": {
"fastify-plugin": "^1.0.1"
},
"devDependencies": {
"fastify": "^2.0.0",
"fastify-cli": "^1.0.0",
"tap": "^12.5.3"
}
}

View File

@ -0,0 +1,483 @@
class Service {
constructor() {}
/**
* 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
**/
async addPet(req, resp) {
console.log("addPet");
// TODO implement this endpoint
return;
};
}
/**
* Deletes a pet
*
* petId Long Pet id to delete
* apiKey String (optional)
* no response value expected for this operation
**/
async deletePet(req, resp) {
console.log("deletePet");
// TODO implement this endpoint
return;
};
}
/**
* 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
**/
async findPetsByStatus(req, resp) {
console.log("findPetsByStatus");
// TODO implement this endpoint
/*return {
"photoUrls" : [ "photoUrls", "photoUrls" ],
"name" : "doggie",
"id" : 0,
"category" : {
"name" : "name",
"id" : 6
},
"tags" : [ {
"name" : "name",
"id" : 1
}, {
"name" : "name",
"id" : 1
} ],
"status" : "available"
};
*/
/*return <Pet>
<id>123456789</id>
<name>doggie</name>
<photoUrls>
<photoUrls>aeiou</photoUrls>
</photoUrls>
<tags>
</tags>
<status>aeiou</status>
</Pet>;
*/
return {};
};
}
/**
* 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
**/
async findPetsByTags(req, resp) {
console.log("findPetsByTags");
// TODO implement this endpoint
/*return {
"photoUrls" : [ "photoUrls", "photoUrls" ],
"name" : "doggie",
"id" : 0,
"category" : {
"name" : "name",
"id" : 6
},
"tags" : [ {
"name" : "name",
"id" : 1
}, {
"name" : "name",
"id" : 1
} ],
"status" : "available"
};
*/
/*return <Pet>
<id>123456789</id>
<name>doggie</name>
<photoUrls>
<photoUrls>aeiou</photoUrls>
</photoUrls>
<tags>
</tags>
<status>aeiou</status>
</Pet>;
*/
return {};
};
}
/**
* Find pet by ID
* Returns a single pet
*
* petId Long ID of pet to return
* returns Pet
**/
async getPetById(req, resp) {
console.log("getPetById");
// TODO implement this endpoint
/*return {
"photoUrls" : [ "photoUrls", "photoUrls" ],
"name" : "doggie",
"id" : 0,
"category" : {
"name" : "name",
"id" : 6
},
"tags" : [ {
"name" : "name",
"id" : 1
}, {
"name" : "name",
"id" : 1
} ],
"status" : "available"
};
*/
/*return <Pet>
<id>123456789</id>
<name>doggie</name>
<photoUrls>
<photoUrls>aeiou</photoUrls>
</photoUrls>
<tags>
</tags>
<status>aeiou</status>
</Pet>;
*/
return {};
};
}
/**
* Update an existing pet
*
* body Pet Pet object that needs to be added to the store
* no response value expected for this operation
**/
async updatePet(req, resp) {
console.log("updatePet");
// TODO implement this endpoint
return;
};
}
/**
* 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
**/
async updatePetWithForm(req, resp) {
console.log("updatePetWithForm");
// TODO implement this endpoint
return;
};
}
/**
* 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
**/
async uploadFile(req, resp) {
console.log("uploadFile");
// TODO implement this endpoint
/*return {
"code" : 0,
"type" : "type",
"message" : "message"
};
*/
return {};
};
}
/**
* 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
**/
async deleteOrder(req, resp) {
console.log("deleteOrder");
// TODO implement this endpoint
return;
};
}
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
*
* returns Map
**/
async getInventory(req, resp) {
console.log("getInventory");
// TODO implement this endpoint
return {};
};
}
/**
* 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
**/
async getOrderById(req, resp) {
console.log("getOrderById");
// TODO implement this endpoint
/*return {
"petId" : 6,
"quantity" : 1,
"id" : 0,
"shipDate" : "2000-01-23T04:56:07.000+00:00",
"complete" : false,
"status" : "placed"
};
*/
/*return <Order>
<id>123456789</id>
<petId>123456789</petId>
<quantity>123</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>aeiou</status>
<complete>true</complete>
</Order>;
*/
return {};
};
}
/**
* Place an order for a pet
*
* body Order order placed for purchasing the pet
* returns Order
**/
async placeOrder(req, resp) {
console.log("placeOrder");
// TODO implement this endpoint
/*return {
"petId" : 6,
"quantity" : 1,
"id" : 0,
"shipDate" : "2000-01-23T04:56:07.000+00:00",
"complete" : false,
"status" : "placed"
};
*/
/*return <Order>
<id>123456789</id>
<petId>123456789</petId>
<quantity>123</quantity>
<shipDate>2000-01-23T04:56:07.000Z</shipDate>
<status>aeiou</status>
<complete>true</complete>
</Order>;
*/
return {};
};
}
/**
* Create user
* This can only be done by the logged in user.
*
* body User Created user object
* no response value expected for this operation
**/
async createUser(req, resp) {
console.log("createUser");
// TODO implement this endpoint
return;
};
}
/**
* Creates list of users with given input array
*
* body List List of user object
* no response value expected for this operation
**/
async createUsersWithArrayInput(req, resp) {
console.log("createUsersWithArrayInput");
// TODO implement this endpoint
return;
};
}
/**
* Creates list of users with given input array
*
* body List List of user object
* no response value expected for this operation
**/
async createUsersWithListInput(req, resp) {
console.log("createUsersWithListInput");
// TODO implement this endpoint
return;
};
}
/**
* 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
**/
async deleteUser(req, resp) {
console.log("deleteUser");
// TODO implement this endpoint
return;
};
}
/**
* Get user by user name
*
* username String The name that needs to be fetched. Use user1 for testing.
* returns User
**/
async getUserByName(req, resp) {
console.log("getUserByName");
// TODO implement this endpoint
/*return {
"firstName" : "firstName",
"lastName" : "lastName",
"password" : "password",
"userStatus" : 6,
"phone" : "phone",
"id" : 0,
"email" : "email",
"username" : "username"
};
*/
/*return <User>
<id>123456789</id>
<username>aeiou</username>
<firstName>aeiou</firstName>
<lastName>aeiou</lastName>
<email>aeiou</email>
<password>aeiou</password>
<phone>aeiou</phone>
<userStatus>123</userStatus>
</User>;
*/
return {};
};
}
/**
* Logs user into the system
*
* username String The user name for login
* password String The password for login in clear text
* returns String
**/
async loginUser(req, resp) {
console.log("loginUser");
// TODO implement this endpoint
return {};
};
}
/**
* Logs out current logged in user session
*
* no response value expected for this operation
**/
async logoutUser(req, resp) {
console.log("logoutUser");
// TODO implement this endpoint
return;
};
}
/**
* 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
**/
async updateUser(req, resp) {
console.log("updateUser");
// TODO implement this endpoint
return;
};
}
module.exports = config => new Service();