[C++] Server Stub Code Generator based on Pistache (#5838)

* Added C++ generator for Pistache

* Revert of CodegenOperation

* Updated template

* Removed isRestful from method declaration

* Updated httpMethod variable

* Changed isRestfulCreate
This commit is contained in:
Sebastiano Miano 2017-06-14 16:40:00 +02:00 committed by wing328
parent 4b9988c4f2
commit e66eceeaaa
49 changed files with 4393 additions and 5 deletions

31
bin/pistache-server-petstore.sh Executable file
View File

@ -0,0 +1,31 @@
#!/usr/bin/env bash
SCRIPT="$0"
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/swagger-codegen-cli/target/swagger-codegen-cli.jar"
if [ ! -f "$executable" ]
then
mvn 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 -l pistache-server -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -o samples/server/petstore/pistache-server"
java $JAVA_OPTS -jar $executable $ags

View File

@ -117,7 +117,7 @@ public class CodegenOperation {
* @return true if act as Restful show method, false otherwise
*/
public boolean isRestfulShow() {
return "GET".equals(httpMethod) && isMemberPath();
return "GET".equalsIgnoreCase(httpMethod) && isMemberPath();
}
/**
@ -126,7 +126,7 @@ public class CodegenOperation {
* @return true if act as Restful create method, false otherwise
*/
public boolean isRestfulCreate() {
return "POST".equals(httpMethod) && "".equals(pathWithoutBaseName());
return "POST".equalsIgnoreCase(httpMethod) && "".equals(pathWithoutBaseName());
}
/**
@ -135,7 +135,7 @@ public class CodegenOperation {
* @return true if act as Restful update method, false otherwise
*/
public boolean isRestfulUpdate() {
return Arrays.asList("PUT", "PATCH").contains(httpMethod) && isMemberPath();
return Arrays.asList("PUT", "PATCH").contains(httpMethod.toUpperCase()) && isMemberPath();
}
/**
@ -144,7 +144,7 @@ public class CodegenOperation {
* @return true if act as Restful destroy method, false otherwise
*/
public boolean isRestfulDestroy() {
return "DELETE".equals(httpMethod) && isMemberPath();
return "DELETE".equalsIgnoreCase(httpMethod) && isMemberPath();
}
/**
@ -172,7 +172,6 @@ public class CodegenOperation {
*/
private boolean isMemberPath() {
if (pathParams.size() != 1) return false;
String id = pathParams.get(0).baseName;
return ("/{" + id + "}").equals(pathWithoutBaseName());
}

View File

@ -0,0 +1,412 @@
package io.swagger.codegen.languages;
import io.swagger.codegen.*;
import io.swagger.models.Model;
import io.swagger.models.Operation;
import io.swagger.models.Response;
import io.swagger.models.Swagger;
import io.swagger.models.properties.*;
import javax.validation.constraints.Null;
import java.util.*;
public class PistacheServerCodegen extends DefaultCodegen implements CodegenConfig {
protected String implFolder = "impl";
@Override
public CodegenType getTag() {
return CodegenType.SERVER;
}
@Override
public String getName() {
return "pistache-server";
}
@Override
public String getHelp() {
return "Generates a C++ API server (based on Pistache)";
}
public PistacheServerCodegen() {
super();
apiPackage = "io.swagger.server.api";
modelPackage = "io.swagger.server.model";
modelTemplateFiles.put("model-header.mustache", ".h");
modelTemplateFiles.put("model-source.mustache", ".cpp");
apiTemplateFiles.put("api-header.mustache", ".h");
apiTemplateFiles.put("api-source.mustache", ".cpp");
apiTemplateFiles.put("api-impl-header.mustache", ".h");
apiTemplateFiles.put("api-impl-source.mustache", ".cpp");
apiTemplateFiles.put("main-api-server.mustache", ".cpp");
embeddedTemplateDir = templateDir = "pistache-server";
cliOptions.clear();
reservedWords = new HashSet<>();
supportingFiles.add(new SupportingFile("modelbase-header.mustache", "model", "ModelBase.h"));
supportingFiles.add(new SupportingFile("modelbase-source.mustache", "model", "ModelBase.cpp"));
supportingFiles.add(new SupportingFile("cmake.mustache", "", "CMakeLists.txt"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList("int", "char", "bool", "long", "float", "double", "int32_t", "int64_t"));
typeMapping = new HashMap<String, String>();
typeMapping.put("date", "std::string");
typeMapping.put("DateTime", "std::string");
typeMapping.put("string", "std::string");
typeMapping.put("integer", "int32_t");
typeMapping.put("long", "int64_t");
typeMapping.put("boolean", "bool");
typeMapping.put("array", "std::vector");
typeMapping.put("map", "std::map");
typeMapping.put("file", "std::string");
typeMapping.put("object", "Object");
typeMapping.put("binary", "std::string");
typeMapping.put("number", "double");
typeMapping.put("UUID", "std::string");
super.importMapping = new HashMap<String, String>();
importMapping.put("std::vector", "#include <vector>");
importMapping.put("std::map", "#include <map>");
importMapping.put("std::string", "#include <string>");
importMapping.put("Object", "#include \"Object.h\"");
}
@Override
public void processOpts() {
super.processOpts();
additionalProperties.put("modelNamespaceDeclarations", modelPackage.split("\\."));
additionalProperties.put("modelNamespace", modelPackage.replaceAll("\\.", "::"));
additionalProperties.put("apiNamespaceDeclarations", apiPackage.split("\\."));
additionalProperties.put("apiNamespace", apiPackage.replaceAll("\\.", "::"));
}
/**
* 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
public String escapeReservedWord(String name) {
return "_" + name; // add an underscore to the name
}
@Override
public String toModelImport(String name) {
if (importMapping.containsKey(name)) {
return importMapping.get(name);
} else {
return "#include \"" + name + ".h\"";
}
}
@Override
public CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions) {
CodegenModel codegenModel = super.fromModel(name, model, allDefinitions);
Set<String> oldImports = codegenModel.imports;
codegenModel.imports = new HashSet<>();
for (String imp : oldImports) {
String newImp = toModelImport(imp);
if (!newImp.isEmpty()) {
codegenModel.imports.add(newImp);
}
}
return codegenModel;
}
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation,
Map<String, Model> definitions, Swagger swagger) {
CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger);
if (operation.getResponses() != null && !operation.getResponses().isEmpty()) {
Response methodResponse = findMethodResponse(operation.getResponses());
if (methodResponse != null) {
if (methodResponse.getSchema() != null) {
CodegenProperty cm = fromProperty("response", methodResponse.getSchema());
op.vendorExtensions.put("x-codegen-response", cm);
if(cm.datatype == "HttpContent")
{
op.vendorExtensions.put("x-codegen-response-ishttpcontent", true);
}
}
}
}
String pathForPistache = path.replaceAll("\\{(.*?)}", ":$1");
op.vendorExtensions.put("x-codegen-pistache-path", pathForPistache);
return op;
}
@SuppressWarnings("unchecked")
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
String classname = (String) operations.get("classname");
operations.put("classnameSnakeUpperCase", DefaultCodegen.underscore(classname).toUpperCase());
operations.put("classnameSnakeLowerCase", DefaultCodegen.underscore(classname).toLowerCase());
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation op : operationList) {
boolean consumeJson = false;
boolean isParsingSupported = true;
if (op.bodyParam != null) {
if (op.bodyParam.vendorExtensions == null) {
op.bodyParam.vendorExtensions = new HashMap<>();
}
op.bodyParam.vendorExtensions.put("x-codegen-pistache-isStringOrDate", op.bodyParam.isString || op.bodyParam.isDate);
}
if(op.consumes != null) {
for (Map<String, String> consume : op.consumes) {
if (consume.get("mediaType") != null && consume.get("mediaType").equals("application/json")) {
consumeJson = true;
}
}
}
op.httpMethod = op.httpMethod.substring(0, 1).toUpperCase() + op.httpMethod.substring(1).toLowerCase();
for(CodegenParameter param : op.allParams){
if (param.isFormParam) isParsingSupported=false;
if (param.isFile) isParsingSupported=false;
if (param.isCookieParam) isParsingSupported=false;
//TODO: This changes the info about the real type but it is needed to parse the header params
if (param.isHeaderParam) {
param.dataType = "Optional<Net::Http::Header::Raw>";
param.baseType = "Optional<Net::Http::Header::Raw>";
} else if(param.isQueryParam){
if(param.isPrimitiveType) {
param.dataType = "Optional<" + param.dataType + ">";
} else {
param.dataType = "Optional<" + param.baseType + ">";
param.baseType = "Optional<" + param.baseType + ">";
}
}
}
if (op.vendorExtensions == null) {
op.vendorExtensions = new HashMap<>();
}
op.vendorExtensions.put("x-codegen-pistache-consumesJson", consumeJson);
op.vendorExtensions.put("x-codegen-pistache-isParsingSupported", isParsingSupported);
}
return objs;
}
@Override
public String toModelFilename(String name) {
return initialCaps(name);
}
@Override
public String apiFilename(String templateName, String tag) {
String result = super.apiFilename(templateName, tag);
if ( templateName.endsWith("impl-header.mustache") ) {
int ix = result.lastIndexOf('/');
result = result.substring(0, ix) + result.substring(ix, result.length() - 2) + "Impl.h";
result = result.replace(apiFileFolder(), implFileFolder());
} else if ( templateName.endsWith("impl-source.mustache") ) {
int ix = result.lastIndexOf('/');
result = result.substring(0, ix) + result.substring(ix, result.length() - 4) + "Impl.cpp";
result = result.replace(apiFileFolder(), implFileFolder());
} else if ( templateName.endsWith("api-server.mustache") ) {
int ix = result.lastIndexOf('/');
result = result.substring(0, ix) + result.substring(ix, result.length() - 4) + "MainServer.cpp";
result = result.replace(apiFileFolder(), outputFolder);
}
return result;
}
@Override
public String toApiFilename(String name) {
return initialCaps(name) + "Api";
}
/**
* Optional - type declaration. This is a String which is used by the
* templates to instantiate your types. There is typically special handling
* for different property types
*
* @return a string value used as the `dataType` field for model templates,
* `returnType` for api templates
*/
@Override
public String getTypeDeclaration(Property p) {
String swaggerType = getSwaggerType(p);
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
}
if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "<std::string, " + getTypeDeclaration(inner) + ">";
}
if (p instanceof StringProperty || p instanceof DateProperty
|| p instanceof DateTimeProperty || p instanceof FileProperty
|| languageSpecificPrimitives.contains(swaggerType)) {
return toModelName(swaggerType);
}
return "std::shared_ptr<" + swaggerType + ">";
}
@Override
public String toDefaultValue(Property p) {
if (p instanceof StringProperty) {
return "\"\"";
} else if (p instanceof BooleanProperty) {
return "false";
} else if (p instanceof DateProperty) {
return "\"\"";
} else if (p instanceof DateTimeProperty) {
return "\"\"";
} else if (p instanceof DoubleProperty) {
return "0.0";
} else if (p instanceof FloatProperty) {
return "0.0f";
} else if (p instanceof IntegerProperty || p instanceof BaseIntegerProperty) {
return "0";
} else if (p instanceof LongProperty) {
return "0L";
} else if (p instanceof DecimalProperty) {
return "0.0";
} else if (p instanceof MapProperty) {
MapProperty ap = (MapProperty) p;
String inner = getSwaggerType(ap.getAdditionalProperties());
return "std::map<std::string, " + inner + ">()";
} else if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
String inner = getSwaggerType(ap.getItems());
if (!languageSpecificPrimitives.contains(inner)) {
inner = "std::shared_ptr<" + inner + ">";
}
return "std::vector<" + inner + ">()";
} else if (p instanceof RefProperty) {
RefProperty rp = (RefProperty) p;
return "new " + toModelName(rp.getSimpleRef()) + "()";
}
return "nullptr";
}
@Override
public void postProcessParameter(CodegenParameter parameter) {
super.postProcessParameter(parameter);
boolean isPrimitiveType = parameter.isPrimitiveType == Boolean.TRUE;
boolean isListContainer = parameter.isListContainer == Boolean.TRUE;
boolean isString = parameter.isString == Boolean.TRUE;
if (!isPrimitiveType && !isListContainer && !isString && !parameter.dataType.startsWith("std::shared_ptr")) {
parameter.dataType = "std::shared_ptr<" + parameter.dataType + ">";
}
}
/**
* Location to write model files. You can use the modelPackage() as defined
* when the class is instantiated
*/
public String modelFileFolder() {
return outputFolder + "/model";
}
/**
* Location to write api files. You can use the apiPackage() as defined when
* the class is instantiated
*/
@Override
public String apiFileFolder() {
return outputFolder + "/api";
}
private String implFileFolder() {
return outputFolder + "/" + implFolder;
}
/**
* Optional - swagger type conversion. This is used to map swagger types in
* a `Property` into either language specific types via `typeMapping` or
* into complex models if there is not a mapping.
*
* @return a string value of the type or complex model for this property
* @see io.swagger.models.properties.Property
*/
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type))
return toModelName(type);
} else
type = swaggerType;
return toModelName(type);
}
@Override
public String toModelName(String type) {
if (typeMapping.keySet().contains(type) || typeMapping.values().contains(type)
|| importMapping.values().contains(type) || defaultIncludes.contains(type)
|| languageSpecificPrimitives.contains(type)) {
return type;
} else {
return Character.toUpperCase(type.charAt(0)) + type.substring(1);
}
}
@Override
public String toVarName(String name) {
if (typeMapping.keySet().contains(name) || typeMapping.values().contains(name)
|| importMapping.values().contains(name) || defaultIncludes.contains(name)
|| languageSpecificPrimitives.contains(name)) {
return name;
}
if (name.length() > 1) {
return Character.toUpperCase(name.charAt(0)) + name.substring(1);
}
return name;
}
@Override
public String toApiName(String type) {
return Character.toUpperCase(type.charAt(0)) + type.substring(1) + "Api";
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
}

View File

@ -42,6 +42,7 @@ io.swagger.codegen.languages.NodeJSServerCodegen
io.swagger.codegen.languages.ObjcClientCodegen
io.swagger.codegen.languages.PerlClientCodegen
io.swagger.codegen.languages.PhpClientCodegen
io.swagger.codegen.languages.PistacheServerCodegen
io.swagger.codegen.languages.PythonClientCodegen
io.swagger.codegen.languages.Qt5CPPGenerator
io.swagger.codegen.languages.Rails5ServerCodegen

View File

@ -0,0 +1,50 @@
# REST API Server for {{appName}}
## Overview
This API Server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project.
It uses the [Pistache](https://github.com/oktal/pistache) Framework.
## Files organization
The Pistache C++ REST server generator creates three folders:
- `api`: This folder contains the handlers for each method specified in the swagger definition. Every handler extracts
the path and body parameters (if any) from the requests and tries to parse and possibly validate them.
Once this step is completed, the main API class calls the corresponding abstract method that should be implemented
by the developer (a basic implementation is provided under the `impl` folder)
- `impl`: As written above, the implementation folder contains, for each API, the corresponding implementation class,
which extends the main API class and implements the abstract methods.
Every method receives the path and body parameters as constant reference variables and a reference to the response
object, that should be filled with the right response and sent at the end of the method with the command:
response.send(returnCode, responseBody, [mimeType])
- `model`: This folder contains the corresponding class for every object schema found in the swagger specification.
The main folder contains also a file with a main that can be used to start the server.
Of course, is you should customize this file based on your needs
## Installation
First of all, you need to download and install the libraries listed [here](#libraries-required).
Once the libraries are installed, in order to compile and run the server please follow the steps below:
```bash
mkdir build
cd build
cmake ..
make
```
Once compiled run the server:
```bash
cd build
./server
```
## Libraries required
- [pistache](http://pistache.io/quickstart)
- [JSON for Modern C++](https://github.com/nlohmann/json/#integration): Please download the `json.hpp` file and
put it under the model folder
## Namespaces
io::swagger::server::api
io::swagger::server::model

View File

@ -0,0 +1,74 @@
{{>licenseInfo}}
{{#operations}}/*
* {{classname}}.h
*
* {{description}}
*/
#ifndef {{classname}}_H_
#define {{classname}}_H_
{{{defaultInclude}}}
#include <pistache/endpoint.h>
#include <pistache/http.h>
#include <pistache/router.h>
#include <pistache/http_headers.h>
{{#imports}}{{{import}}}
{{/imports}}
{{#apiNamespaceDeclarations}}
namespace {{this}} {
{{/apiNamespaceDeclarations}}
using namespace {{modelNamespace}};
class {{declspec}} {{classname}} {
public:
{{classname}}(Net::Address addr);
virtual ~{{classname}}() {};
void init(size_t thr);
void start();
void shutdown();
const std::string base = "{{basePathWithoutHost}}";
private:
void setupRoutes();
{{#operation}}
void {{operationIdSnakeCase}}_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response);
{{/operation}}
void {{classnameSnakeLowerCase}}_default_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response);
std::shared_ptr<Net::Http::Endpoint> httpEndpoint;
Net::Rest::Router router;
{{#operation}}
/// <summary>
/// {{summary}}
/// </summary>
/// <remarks>
/// {{notes}}
/// </remarks>
{{#vendorExtensions.x-codegen-pistache-isParsingSupported}}
{{#allParams}}
/// <param name="{{paramName}}">{{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}</param>
{{/allParams}}
virtual void {{operationIdSnakeCase}}({{#allParams}}const {{#isPrimitiveType}}{{{dataType}}}{{/isPrimitiveType}}{{^isPrimitiveType}}{{{baseType}}}{{/isPrimitiveType}} &{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}Net::Http::ResponseWriter &response) = 0;
{{/vendorExtensions.x-codegen-pistache-isParsingSupported}}
{{^vendorExtensions.x-codegen-pistache-isParsingSupported}}
virtual void {{operationIdSnakeCase}}(const Net::Rest::Request &request, Net::Http::ResponseWriter &response) = 0;
{{/vendorExtensions.x-codegen-pistache-isParsingSupported}}
{{/operation}}
};
{{#apiNamespaceDeclarations}}
}
{{/apiNamespaceDeclarations}}
#endif /* {{classname}}_H_ */
{{/operations}}

View File

@ -0,0 +1,52 @@
{{>licenseInfo}}
{{#operations}}/*
* {{classname}}Impl.h
*
* {{description}}
*/
#ifndef {{classnameSnakeUpperCase}}_IMPL_H_
#define {{classnameSnakeUpperCase}}_IMPL_H_
{{{defaultInclude}}}
#include <pistache/endpoint.h>
#include <pistache/http.h>
#include <pistache/router.h>
#include <memory>
#include <{{classname}}.h>
{{#imports}}{{{import}}}
{{/imports}}
{{#apiNamespaceDeclarations}}
namespace {{this}} {
{{/apiNamespaceDeclarations}}
using namespace {{modelNamespace}};
class {{classname}}Impl : public {{apiNamespace}}::{{classname}} {
public:
{{classname}}Impl(Net::Address addr);
~{{classname}}Impl() { };
{{#operation}}
{{#vendorExtensions.x-codegen-pistache-isParsingSupported}}
void {{operationIdSnakeCase}}({{#allParams}}const {{#isPrimitiveType}}{{{dataType}}}{{/isPrimitiveType}}{{^isPrimitiveType}}{{{baseType}}}{{/isPrimitiveType}} &{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}Net::Http::ResponseWriter &response);
{{/vendorExtensions.x-codegen-pistache-isParsingSupported}}
{{^vendorExtensions.x-codegen-pistache-isParsingSupported}}
void {{operationIdSnakeCase}}(const Net::Rest::Request &request, Net::Http::ResponseWriter &response);
{{/vendorExtensions.x-codegen-pistache-isParsingSupported}}
{{/operation}}
};
{{#apiNamespaceDeclarations}}
}
{{/apiNamespaceDeclarations}}
{{/operations}}
#endif

View File

@ -0,0 +1,33 @@
{{>licenseInfo}}
{{#operations}}
#include "{{classname}}Impl.h"
{{#apiNamespaceDeclarations}}
namespace {{this}} {
{{/apiNamespaceDeclarations}}
using namespace {{modelNamespace}};
{{classname}}Impl::{{classname}}Impl(Net::Address addr)
: {{classname}}(addr)
{ }
{{#operation}}
{{#vendorExtensions.x-codegen-pistache-isParsingSupported}}
void {{classname}}Impl::{{operationIdSnakeCase}}({{#allParams}}const {{#isPrimitiveType}}{{{dataType}}}{{/isPrimitiveType}}{{^isPrimitiveType}}{{{baseType}}}{{/isPrimitiveType}} &{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}Net::Http::ResponseWriter &response) {
response.send(Net::Http::Code::Ok, "Do some magic\n");
}
{{/vendorExtensions.x-codegen-pistache-isParsingSupported}}
{{^vendorExtensions.x-codegen-pistache-isParsingSupported}}
void {{classname}}Impl::{{operationIdSnakeCase}}(const Net::Rest::Request &request, Net::Http::ResponseWriter &response){
response.send(Net::Http::Code::Ok, "Do some magic\n");
}
{{/vendorExtensions.x-codegen-pistache-isParsingSupported}}
{{/operation}}
{{#apiNamespaceDeclarations}}
}
{{/apiNamespaceDeclarations}}
{{/operations}}

View File

@ -0,0 +1,108 @@
{{>licenseInfo}}
{{#operations}}
#include "{{classname}}.h"
{{#apiNamespaceDeclarations}}
namespace {{this}} {
{{/apiNamespaceDeclarations}}
using namespace {{modelNamespace}};
{{classname}}::{{classname}}(Net::Address addr)
: httpEndpoint(std::make_shared<Net::Http::Endpoint>(addr))
{ };
void {{classname}}::init(size_t thr = 2) {
auto opts = Net::Http::Endpoint::options()
.threads(thr)
.flags(Net::Tcp::Options::InstallSignalHandler);
httpEndpoint->init(opts);
setupRoutes();
}
void {{classname}}::start() {
httpEndpoint->setHandler(router.handler());
httpEndpoint->serve();
}
void {{classname}}::shutdown() {
httpEndpoint->shutdown();
}
void {{classname}}::setupRoutes() {
using namespace Net::Rest;
{{#operation}}
Routes::{{httpMethod}}(router, base + "{{{vendorExtensions.x-codegen-pistache-path}}}", Routes::bind(&{{classname}}::{{operationIdSnakeCase}}_handler, this));
{{/operation}}
// Default handler, called when a route is not found
router.addCustomHandler(Routes::bind(&{{classname}}::{{classnameSnakeLowerCase}}_default_handler, this));
}
{{#operation}}
void {{classname}}::{{operationIdSnakeCase}}_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response) {
{{#vendorExtensions.x-codegen-pistache-isParsingSupported}}
{{#hasPathParams}}
// Getting the path params
{{#pathParams}}
auto {{paramName}} = request.param(":{{paramName}}").as<{{dataType}}>();
{{/pathParams}}
{{/hasPathParams}}{{#hasBodyParam}}
// Getting the body param
{{#bodyParam}}
{{^isPrimitiveType}}
{{baseType}} {{paramName}};{{/isPrimitiveType}}
{{#isPrimitiveType}}
{{dataType}} {{paramName}};
{{/isPrimitiveType}}
{{/bodyParam}}
{{/hasBodyParam}}{{#hasQueryParams}}
// Getting the query params
{{#queryParams}}
auto {{paramName}} = request.query().get("{{baseName}}");
{{/queryParams}}
{{/hasQueryParams}}{{#hasHeaderParams}}
// Getting the header params
{{#headerParams}}
auto {{paramName}} = request.headers().tryGetRaw("{{baseName}}");
{{/headerParams}}
{{/hasHeaderParams}}
try {
{{#hasBodyParam}}
{{#bodyParam}}
nlohmann::json request_body = nlohmann::json::parse(request.body());
{{^isPrimitiveType}}
{{paramName}}.fromJson(request_body); {{/isPrimitiveType}}
{{#isPrimitiveType}}
// The conversion is done automatically by the json library
{{paramName}} = request_body;
{{/isPrimitiveType}}
{{/bodyParam}}
{{/hasBodyParam}}
this->{{operationIdSnakeCase}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}response);
{{/vendorExtensions.x-codegen-pistache-isParsingSupported}}
{{^vendorExtensions.x-codegen-pistache-isParsingSupported}}
try {
this->{{operationIdSnakeCase}}(request, response);
{{/vendorExtensions.x-codegen-pistache-isParsingSupported}}
} catch (std::runtime_error & e) {
//send a 400 error
response.send(Net::Http::Code::Bad_Request, e.what());
return;
}
}
{{/operation}}
void {{classname}}::{{classnameSnakeLowerCase}}_default_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response) {
response.send(Net::Http::Code::Not_Found, "The requested method does not exist");
}
{{#apiNamespaceDeclarations}}
}
{{/apiNamespaceDeclarations}}
{{/operations}}

View File

@ -0,0 +1,48 @@
cmake_minimum_required (VERSION 3.2)
project(server)
set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} -std=c++11)
link_directories(/usr/local/lib/)
aux_source_directory(model MODEL_SOURCES)
{{=<% %>=}}
<%#apiInfo.apis%>
<%#operations%>
file(GLOB <%classnameSnakeUpperCase%>_SOURCES
"api/<%classname%>.h"
"api/<%classname%>.cpp"
"impl/<%classname%>Impl.h"
"impl/<%classname%>Impl.cpp"
)
<%/operations%>
<%/apiInfo.apis%>
include_directories(model)
include_directories(api)
include_directories(impl)
<%#apiInfo.apis%>
<%#operations%>
set(<%classnameSnakeUpperCase%>_SERVER_SOURCES
<%classname%>MainServer.cpp
${MODEL_SOURCES}
${<%classnameSnakeUpperCase%>_SOURCES})
<%/operations%>
<%/apiInfo.apis%>
<%#apiInfo.apis%>
<%#operations%>
add_executable(<%classnameSnakeLowerCase%>_server
${<%classnameSnakeUpperCase%>_SERVER_SOURCES})
<%/operations%>
<%/apiInfo.apis%>
<%#apiInfo.apis%>
<%#operations%>
target_link_libraries(<%classnameSnakeLowerCase%>_server net)
<%/operations%>
<%/apiInfo.apis%>
<%={{ }}=%>

View File

@ -0,0 +1,11 @@
/**
* {{{appName}}}
* {{{appDescription}}}
*
* {{#version}}OpenAPI spec version: {{{version}}}{{/version}}
* {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}}
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/

View File

@ -0,0 +1,21 @@
{{>licenseInfo}}
{{#operations}}
#include "pistache/endpoint.h"
#include "pistache/http.h"
#include "pistache/router.h"
#include "{{classname}}Impl.h"
using namespace {{apiNamespace}};
int main() {
Net::Address addr(Net::Ipv4::any(), Net::Port(8080));
{{classname}}Impl server(addr);
server.init(2);
server.start();
server.shutdown();
}
{{/operations}}

View File

@ -0,0 +1,68 @@
{{>licenseInfo}}
{{#models}}{{#model}}/*
* {{classname}}.h
*
* {{description}}
*/
#ifndef {{classname}}_H_
#define {{classname}}_H_
{{{defaultInclude}}}
#include "ModelBase.h"
{{#imports}}{{{this}}}
{{/imports}}
{{#modelNamespaceDeclarations}}
namespace {{this}} {
{{/modelNamespaceDeclarations}}
/// <summary>
/// {{description}}
/// </summary>
class {{declspec}} {{classname}}
: public ModelBase
{
public:
{{classname}}();
virtual ~{{classname}}();
/////////////////////////////////////////////
/// ModelBase overrides
void validate() override;
nlohmann::json toJson() const override;
void fromJson(nlohmann::json& json) override;
/////////////////////////////////////////////
/// {{classname}} members
{{#vars}}
/// <summary>
/// {{description}}
/// </summary>
{{^isNotContainer}}{{{datatype}}}& {{getter}}();
{{/isNotContainer}}{{#isNotContainer}}{{{datatype}}} {{getter}}() const;
void {{setter}}({{{datatype}}} value);
{{/isNotContainer}}{{^required}}bool {{baseName}}IsSet() const;
void unset{{name}}();
{{/required}}
{{/vars}}
protected:
{{#vars}}
{{{datatype}}} m_{{name}};
{{^required}}
bool m_{{name}}IsSet;{{/required}}
{{/vars}}
};
{{#modelNamespaceDeclarations}}
}
{{/modelNamespaceDeclarations}}
#endif /* {{classname}}_H_ */
{{/model}}
{{/models}}

View File

@ -0,0 +1,144 @@
{{>licenseInfo}}
{{#models}}{{#model}}
#include "{{classname}}.h"
{{#modelNamespaceDeclarations}}
namespace {{this}} {
{{/modelNamespaceDeclarations}}
{{classname}}::{{classname}}()
{
{{#vars}}{{#isNotContainer}}{{#isPrimitiveType}}m_{{name}} = {{{defaultValue}}};
{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isString}}m_{{name}} = {{{defaultValue}}};
{{/isString}}{{#isDateTime}}m_{{name}} = {{{defaultValue}}};
{{/isDateTime}}{{/isPrimitiveType}}{{/isNotContainer}}{{^required}}m_{{name}}IsSet = false;
{{/required}}{{/vars}}
}
{{classname}}::~{{classname}}()
{
}
void {{classname}}::validate()
{
// TODO: implement validation
}
nlohmann::json {{classname}}::toJson() const
{
nlohmann::json val = nlohmann::json::object();
{{#vars}}{{#isPrimitiveType}}{{^isListContainer}}{{^required}}if(m_{{name}}IsSet)
{
val["{{baseName}}"] = m_{{name}};
}
{{/required}}{{#required}}val["{{baseName}}"] = m_{{name}};
{{/required}}{{/isListContainer}}{{/isPrimitiveType}}{{#isListContainer}}{
nlohmann::json jsonArray;
for( auto& item : m_{{name}} )
{
jsonArray.push_back(ModelBase::toJson(item));
}
{{#required}}val["{{baseName}}"] = jsonArray;
{{/required}}{{^required}}
if(jsonArray.size() > 0)
{
val["{{baseName}}"] = jsonArray;
}
{{/required}}
}
{{/isListContainer}}{{^isListContainer}}{{^isPrimitiveType}}{{^required}}if(m_{{name}}IsSet)
{
val["{{baseName}}"] = ModelBase::toJson(m_{{name}});
}
{{/required}}{{#required}}val["{{baseName}}"] = ModelBase::toJson(m_{{name}});
{{/required}}{{/isPrimitiveType}}{{/isListContainer}}{{/vars}}
return val;
}
void {{classname}}::fromJson(nlohmann::json& val)
{
{{#vars}}{{#isPrimitiveType}}{{^isListContainer}}{{^required}}if(val.find("{{baseName}}") != val.end())
{
{{setter}}(val.at("{{baseName}}"));
}
{{/required}}{{#required}}{{setter}}(val.at("{{baseName}}"));
{{/required}}{{/isListContainer}}{{/isPrimitiveType}}{{#isListContainer}}{
m_{{name}}.clear();
nlohmann::json jsonArray;
{{^required}}if(val.find("{{baseName}}") != val.end())
{
{{/required}}
for( auto& item : val["{{baseName}}"] )
{
{{#isPrimitiveType}}m_{{name}}.push_back(item);
{{/isPrimitiveType}}{{^isPrimitiveType}}{{#items.isString}}m_{{name}}.push_back(item);
{{/items.isString}}{{^items.isString}}{{#items.isDateTime}}m_{{name}}.push_back(item);
{{/items.isDateTime}}{{^items.isDateTime}}
if(item.is_null())
{
m_{{name}}.push_back( {{{items.datatype}}}(nullptr) );
}
else
{
{{{items.datatype}}} newItem({{{items.defaultValue}}});
newItem->fromJson(item);
m_{{name}}.push_back( newItem );
}
{{/items.isDateTime}}{{/items.isString}}{{/isPrimitiveType}}
}
{{^required}}
}
{{/required}}
}
{{/isListContainer}}{{^isListContainer}}{{^isPrimitiveType}}{{^required}}if(val.find("{{baseName}}") != val.end())
{
{{#isString}}{{setter}}(val.at("{{baseName}}"));
{{/isString}}{{^isString}}{{#isDateTime}}{{setter}}(val.at("{{baseName}}"));
{{/isDateTime}}{{^isDateTime}}if(!val["{{baseName}}"].is_null())
{
{{{datatype}}} newItem({{{defaultValue}}});
newItem->fromJson(val["{{baseName}}"]);
{{setter}}( newItem );
}
{{/isDateTime}}{{/isString}}
}
{{/required}}{{#required}}{{#isString}}{{setter}}(val.at("{{baseName}}"));
{{/isString}}{{^isString}}{{#isDateTime}}{{setter}}(val.at("{{baseName}}"));
{{/isDateTime}}{{/isString}}{{/required}}{{/isPrimitiveType}}{{/isListContainer}}{{/vars}}
}
{{#vars}}{{^isNotContainer}}{{{datatype}}}& {{classname}}::{{getter}}()
{
return m_{{name}};
}
{{/isNotContainer}}{{#isNotContainer}}{{{datatype}}} {{classname}}::{{getter}}() const
{
return m_{{name}};
}
void {{classname}}::{{setter}}({{{datatype}}} value)
{
m_{{name}} = value;
{{^required}}m_{{name}}IsSet = true;{{/required}}
}
{{/isNotContainer}}
{{^required}}bool {{classname}}::{{baseName}}IsSet() const
{
return m_{{name}}IsSet;
}
void {{classname}}::unset{{name}}()
{
m_{{name}}IsSet = false;
}
{{/required}}
{{/vars}}
{{#modelNamespaceDeclarations}}
}
{{/modelNamespaceDeclarations}}
{{/model}}
{{/models}}

View File

@ -0,0 +1,45 @@
{{>licenseInfo}}
/*
* ModelBase.h
*
* This is the base class for all model classes
*/
#ifndef ModelBase_H_
#define ModelBase_H_
{{{defaultInclude}}}
#include "json.hpp"
#include <ctime>
#include <string>
{{#modelNamespaceDeclarations}}
namespace {{this}} {
{{/modelNamespaceDeclarations}}
class {{declspec}} ModelBase
{
public:
ModelBase();
virtual ~ModelBase();
virtual void validate() = 0;
virtual nlohmann::json toJson() const = 0;
virtual void fromJson(nlohmann::json& json) = 0;
static std::string toJson( const std::string& value );
static std::string toJson( const std::time_t& value );
static int32_t toJson( int32_t value );
static int64_t toJson( int64_t value );
static double toJson( double value );
static bool toJson( bool value );
static nlohmann::json toJson( std::shared_ptr<ModelBase> content );
};
{{#modelNamespaceDeclarations}}
}
{{/modelNamespaceDeclarations}}
#endif /* ModelBase_H_ */

View File

@ -0,0 +1,54 @@
{{>licenseInfo}}
#include "ModelBase.h"
{{#modelNamespaceDeclarations}}
namespace {{this}} {
{{/modelNamespaceDeclarations}}
ModelBase::ModelBase()
{
}
ModelBase::~ModelBase()
{
}
std::string ModelBase::toJson( const std::string& value )
{
return value;
}
std::string ModelBase::toJson( const std::time_t& value )
{
char buf[sizeof "2011-10-08T07:07:09Z"];
strftime(buf, sizeof buf, "%FT%TZ", gmtime(&value));
return buf;
}
int32_t ModelBase::toJson( int32_t value )
{
return value;
}
int64_t ModelBase::toJson( int64_t value )
{
return value;
}
double ModelBase::toJson( double value )
{
return value;
}
bool ModelBase::toJson( bool value )
{
return value;
}
nlohmann::json ModelBase::toJson( std::shared_ptr<ModelBase> content )
{
return content.get() ? content->toJson() : nlohmann::json();
}
{{#modelNamespaceDeclarations}}
}
{{/modelNamespaceDeclarations}}

View File

@ -0,0 +1,23 @@
# Swagger Codegen Ignore
# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen
# 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 Swagger Codgen 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 @@
2.2.3-SNAPSHOT

View File

@ -0,0 +1,56 @@
cmake_minimum_required (VERSION 3.2)
project(server)
set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} -std=c++11)
link_directories(/usr/local/lib/)
aux_source_directory(model MODEL_SOURCES)
file(GLOB PET_API_SOURCES
"api/PetApi.h"
"api/PetApi.cpp"
"impl/PetApiImpl.h"
"impl/PetApiImpl.cpp"
)
file(GLOB STORE_API_SOURCES
"api/StoreApi.h"
"api/StoreApi.cpp"
"impl/StoreApiImpl.h"
"impl/StoreApiImpl.cpp"
)
file(GLOB USER_API_SOURCES
"api/UserApi.h"
"api/UserApi.cpp"
"impl/UserApiImpl.h"
"impl/UserApiImpl.cpp"
)
include_directories(model)
include_directories(api)
include_directories(impl)
set(PET_API_SERVER_SOURCES
PetApiMainServer.cpp
${MODEL_SOURCES}
${PET_API_SOURCES})
set(STORE_API_SERVER_SOURCES
StoreApiMainServer.cpp
${MODEL_SOURCES}
${STORE_API_SOURCES})
set(USER_API_SERVER_SOURCES
UserApiMainServer.cpp
${MODEL_SOURCES}
${USER_API_SOURCES})
add_executable(pet_api_server
${PET_API_SERVER_SOURCES})
add_executable(store_api_server
${STORE_API_SERVER_SOURCES})
add_executable(user_api_server
${USER_API_SERVER_SOURCES})
target_link_libraries(pet_api_server net)
target_link_libraries(store_api_server net)
target_link_libraries(user_api_server net)

View File

@ -0,0 +1,29 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
#include "pistache/endpoint.h"
#include "pistache/http.h"
#include "pistache/router.h"
#include "PetApiImpl.h"
using namespace io::swagger::server::api;
int main() {
Net::Address addr(Net::Ipv4::any(), Net::Port(8080));
PetApiImpl server(addr);
server.init(2);
server.start();
server.shutdown();
}

View File

@ -0,0 +1,50 @@
# REST API Server for Swagger Petstore
## Overview
This API Server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project.
It uses the [Pistache](https://github.com/oktal/pistache) Framework.
## Files organization
The Pistache C++ REST server generator creates three folders:
- `api`: This folder contains the handlers for each method specified in the swagger definition. Every handler extracts
the path and body parameters (if any) from the requests and tries to parse and possibly validate them.
Once this step is completed, the main API class calls the corresponding abstract method that should be implemented
by the developer (a basic implementation is provided under the `impl` folder)
- `impl`: As written above, the implementation folder contains, for each API, the corresponding implementation class,
which extends the main API class and implements the abstract methods.
Every method receives the path and body parameters as constant reference variables and a reference to the response
object, that should be filled with the right response and sent at the end of the method with the command:
response.send(returnCode, responseBody, [mimeType])
- `model`: This folder contains the corresponding class for every object schema found in the swagger specification.
The main folder contains also a file with a main that can be used to start the server.
Of course, is you should customize this file based on your needs
## Installation
First of all, you need to download and install the libraries listed [here](#libraries-required).
Once the libraries are installed, in order to compile and run the server please follow the steps below:
```bash
mkdir build
cd build
cmake ..
make
```
Once compiled run the server:
```bash
cd build
./server
```
## Libraries required
- [pistache](http://pistache.io/quickstart)
- [JSON for Modern C++](https://github.com/nlohmann/json/#integration): Please download the `json.hpp` file and
put it under the model folder
## Namespaces
io::swagger::server::api
io::swagger::server::model

View File

@ -0,0 +1,29 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
#include "pistache/endpoint.h"
#include "pistache/http.h"
#include "pistache/router.h"
#include "StoreApiImpl.h"
using namespace io::swagger::server::api;
int main() {
Net::Address addr(Net::Ipv4::any(), Net::Port(8080));
StoreApiImpl server(addr);
server.init(2);
server.start();
server.shutdown();
}

View File

@ -0,0 +1,29 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
#include "pistache/endpoint.h"
#include "pistache/http.h"
#include "pistache/router.h"
#include "UserApiImpl.h"
using namespace io::swagger::server::api;
int main() {
Net::Address addr(Net::Ipv4::any(), Net::Port(8080));
UserApiImpl server(addr);
server.init(2);
server.start();
server.shutdown();
}

View File

@ -0,0 +1,177 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
#include "PetApi.h"
namespace io {
namespace swagger {
namespace server {
namespace api {
using namespace io::swagger::server::model;
PetApi::PetApi(Net::Address addr)
: httpEndpoint(std::make_shared<Net::Http::Endpoint>(addr))
{ };
void PetApi::init(size_t thr = 2) {
auto opts = Net::Http::Endpoint::options()
.threads(thr)
.flags(Net::Tcp::Options::InstallSignalHandler);
httpEndpoint->init(opts);
setupRoutes();
}
void PetApi::start() {
httpEndpoint->setHandler(router.handler());
httpEndpoint->serve();
}
void PetApi::shutdown() {
httpEndpoint->shutdown();
}
void PetApi::setupRoutes() {
using namespace Net::Rest;
Routes::Post(router, base + "/pet", Routes::bind(&PetApi::add_pet_handler, this));
Routes::Delete(router, base + "/pet/:petId", Routes::bind(&PetApi::delete_pet_handler, this));
Routes::Get(router, base + "/pet/findByStatus", Routes::bind(&PetApi::find_pets_by_status_handler, this));
Routes::Get(router, base + "/pet/findByTags", Routes::bind(&PetApi::find_pets_by_tags_handler, this));
Routes::Get(router, base + "/pet/:petId", Routes::bind(&PetApi::get_pet_by_id_handler, this));
Routes::Put(router, base + "/pet", Routes::bind(&PetApi::update_pet_handler, this));
Routes::Post(router, base + "/pet/:petId", Routes::bind(&PetApi::update_pet_with_form_handler, this));
Routes::Post(router, base + "/pet/:petId/uploadImage", Routes::bind(&PetApi::upload_file_handler, this));
// Default handler, called when a route is not found
router.addCustomHandler(Routes::bind(&PetApi::pet_api_default_handler, this));
}
void PetApi::add_pet_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response) {
// Getting the body param
Pet body;
try {
nlohmann::json request_body = nlohmann::json::parse(request.body());
body.fromJson(request_body);
this->add_pet(body, response);
} catch (std::runtime_error & e) {
//send a 400 error
response.send(Net::Http::Code::Bad_Request, e.what());
return;
}
}
void PetApi::delete_pet_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response) {
// Getting the path params
auto petId = request.param(":petId").as<int64_t>();
// Getting the header params
auto apiKey = request.headers().tryGetRaw("api_key");
try {
this->delete_pet(petId, apiKey, response);
} catch (std::runtime_error & e) {
//send a 400 error
response.send(Net::Http::Code::Bad_Request, e.what());
return;
}
}
void PetApi::find_pets_by_status_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response) {
// Getting the query params
auto status = request.query().get("status");
try {
this->find_pets_by_status(status, response);
} catch (std::runtime_error & e) {
//send a 400 error
response.send(Net::Http::Code::Bad_Request, e.what());
return;
}
}
void PetApi::find_pets_by_tags_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response) {
// Getting the query params
auto tags = request.query().get("tags");
try {
this->find_pets_by_tags(tags, response);
} catch (std::runtime_error & e) {
//send a 400 error
response.send(Net::Http::Code::Bad_Request, e.what());
return;
}
}
void PetApi::get_pet_by_id_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response) {
// Getting the path params
auto petId = request.param(":petId").as<int64_t>();
try {
this->get_pet_by_id(petId, response);
} catch (std::runtime_error & e) {
//send a 400 error
response.send(Net::Http::Code::Bad_Request, e.what());
return;
}
}
void PetApi::update_pet_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response) {
// Getting the body param
Pet body;
try {
nlohmann::json request_body = nlohmann::json::parse(request.body());
body.fromJson(request_body);
this->update_pet(body, response);
} catch (std::runtime_error & e) {
//send a 400 error
response.send(Net::Http::Code::Bad_Request, e.what());
return;
}
}
void PetApi::update_pet_with_form_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response) {
try {
this->update_pet_with_form(request, response);
} catch (std::runtime_error & e) {
//send a 400 error
response.send(Net::Http::Code::Bad_Request, e.what());
return;
}
}
void PetApi::upload_file_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response) {
try {
this->upload_file(request, response);
} catch (std::runtime_error & e) {
//send a 400 error
response.send(Net::Http::Code::Bad_Request, e.what());
return;
}
}
void PetApi::pet_api_default_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response) {
response.send(Net::Http::Code::Not_Found, "The requested method does not exist");
}
}
}
}
}

View File

@ -0,0 +1,144 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/*
* PetApi.h
*
*
*/
#ifndef PetApi_H_
#define PetApi_H_
#include <pistache/endpoint.h>
#include <pistache/http.h>
#include <pistache/router.h>
#include <pistache/http_headers.h>
#include "ApiResponse.h"
#include "Pet.h"
#include <string>
namespace io {
namespace swagger {
namespace server {
namespace api {
using namespace io::swagger::server::model;
class PetApi {
public:
PetApi(Net::Address addr);
virtual ~PetApi() {};
void init(size_t thr);
void start();
void shutdown();
const std::string base = "/v2";
private:
void setupRoutes();
void add_pet_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response);
void delete_pet_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response);
void find_pets_by_status_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response);
void find_pets_by_tags_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response);
void get_pet_by_id_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response);
void update_pet_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response);
void update_pet_with_form_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response);
void upload_file_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response);
void pet_api_default_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response);
std::shared_ptr<Net::Http::Endpoint> httpEndpoint;
Net::Rest::Router router;
/// <summary>
/// Add a new pet to the store
/// </summary>
/// <remarks>
///
/// </remarks>
/// <param name="body">Pet object that needs to be added to the store</param>
virtual void add_pet(const Pet &body, Net::Http::ResponseWriter &response) = 0;
/// <summary>
/// Deletes a pet
/// </summary>
/// <remarks>
///
/// </remarks>
/// <param name="petId">Pet id to delete</param>
/// <param name="apiKey"> (optional)</param>
virtual void delete_pet(const int64_t &petId, const Optional<Net::Http::Header::Raw> &apiKey, Net::Http::ResponseWriter &response) = 0;
/// <summary>
/// Finds Pets by status
/// </summary>
/// <remarks>
/// Multiple status values can be provided with comma separated strings
/// </remarks>
/// <param name="status">Status values that need to be considered for filter</param>
virtual void find_pets_by_status(const Optional<std::string> &status, Net::Http::ResponseWriter &response) = 0;
/// <summary>
/// Finds Pets by tags
/// </summary>
/// <remarks>
/// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
/// </remarks>
/// <param name="tags">Tags to filter by</param>
virtual void find_pets_by_tags(const Optional<std::string> &tags, Net::Http::ResponseWriter &response) = 0;
/// <summary>
/// Find pet by ID
/// </summary>
/// <remarks>
/// Returns a single pet
/// </remarks>
/// <param name="petId">ID of pet to return</param>
virtual void get_pet_by_id(const int64_t &petId, Net::Http::ResponseWriter &response) = 0;
/// <summary>
/// Update an existing pet
/// </summary>
/// <remarks>
///
/// </remarks>
/// <param name="body">Pet object that needs to be added to the store</param>
virtual void update_pet(const Pet &body, Net::Http::ResponseWriter &response) = 0;
/// <summary>
/// Updates a pet in the store with form data
/// </summary>
/// <remarks>
///
/// </remarks>
virtual void update_pet_with_form(const Net::Rest::Request &request, Net::Http::ResponseWriter &response) = 0;
/// <summary>
/// uploads an image
/// </summary>
/// <remarks>
///
/// </remarks>
virtual void upload_file(const Net::Rest::Request &request, Net::Http::ResponseWriter &response) = 0;
};
}
}
}
}
#endif /* PetApi_H_ */

View File

@ -0,0 +1,117 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
#include "StoreApi.h"
namespace io {
namespace swagger {
namespace server {
namespace api {
using namespace io::swagger::server::model;
StoreApi::StoreApi(Net::Address addr)
: httpEndpoint(std::make_shared<Net::Http::Endpoint>(addr))
{ };
void StoreApi::init(size_t thr = 2) {
auto opts = Net::Http::Endpoint::options()
.threads(thr)
.flags(Net::Tcp::Options::InstallSignalHandler);
httpEndpoint->init(opts);
setupRoutes();
}
void StoreApi::start() {
httpEndpoint->setHandler(router.handler());
httpEndpoint->serve();
}
void StoreApi::shutdown() {
httpEndpoint->shutdown();
}
void StoreApi::setupRoutes() {
using namespace Net::Rest;
Routes::Delete(router, base + "/store/order/:orderId", Routes::bind(&StoreApi::delete_order_handler, this));
Routes::Get(router, base + "/store/inventory", Routes::bind(&StoreApi::get_inventory_handler, this));
Routes::Get(router, base + "/store/order/:orderId", Routes::bind(&StoreApi::get_order_by_id_handler, this));
Routes::Post(router, base + "/store/order", Routes::bind(&StoreApi::place_order_handler, this));
// Default handler, called when a route is not found
router.addCustomHandler(Routes::bind(&StoreApi::store_api_default_handler, this));
}
void StoreApi::delete_order_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response) {
// Getting the path params
auto orderId = request.param(":orderId").as<std::string>();
try {
this->delete_order(orderId, response);
} catch (std::runtime_error & e) {
//send a 400 error
response.send(Net::Http::Code::Bad_Request, e.what());
return;
}
}
void StoreApi::get_inventory_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response) {
try {
this->get_inventory(response);
} catch (std::runtime_error & e) {
//send a 400 error
response.send(Net::Http::Code::Bad_Request, e.what());
return;
}
}
void StoreApi::get_order_by_id_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response) {
// Getting the path params
auto orderId = request.param(":orderId").as<int64_t>();
try {
this->get_order_by_id(orderId, response);
} catch (std::runtime_error & e) {
//send a 400 error
response.send(Net::Http::Code::Bad_Request, e.what());
return;
}
}
void StoreApi::place_order_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response) {
// Getting the body param
Order body;
try {
nlohmann::json request_body = nlohmann::json::parse(request.body());
body.fromJson(request_body);
this->place_order(body, response);
} catch (std::runtime_error & e) {
//send a 400 error
response.send(Net::Http::Code::Bad_Request, e.what());
return;
}
}
void StoreApi::store_api_default_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response) {
response.send(Net::Http::Code::Not_Found, "The requested method does not exist");
}
}
}
}
}

View File

@ -0,0 +1,104 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/*
* StoreApi.h
*
*
*/
#ifndef StoreApi_H_
#define StoreApi_H_
#include <pistache/endpoint.h>
#include <pistache/http.h>
#include <pistache/router.h>
#include <pistache/http_headers.h>
#include "Order.h"
#include <map>
#include <string>
namespace io {
namespace swagger {
namespace server {
namespace api {
using namespace io::swagger::server::model;
class StoreApi {
public:
StoreApi(Net::Address addr);
virtual ~StoreApi() {};
void init(size_t thr);
void start();
void shutdown();
const std::string base = "/v2";
private:
void setupRoutes();
void delete_order_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response);
void get_inventory_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response);
void get_order_by_id_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response);
void place_order_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response);
void store_api_default_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response);
std::shared_ptr<Net::Http::Endpoint> httpEndpoint;
Net::Rest::Router router;
/// <summary>
/// Delete purchase order by ID
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
/// </remarks>
/// <param name="orderId">ID of the order that needs to be deleted</param>
virtual void delete_order(const std::string &orderId, Net::Http::ResponseWriter &response) = 0;
/// <summary>
/// Returns pet inventories by status
/// </summary>
/// <remarks>
/// Returns a map of status codes to quantities
/// </remarks>
virtual void get_inventory(Net::Http::ResponseWriter &response) = 0;
/// <summary>
/// Find purchase order by ID
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generated exceptions
/// </remarks>
/// <param name="orderId">ID of pet that needs to be fetched</param>
virtual void get_order_by_id(const int64_t &orderId, Net::Http::ResponseWriter &response) = 0;
/// <summary>
/// Place an order for a pet
/// </summary>
/// <remarks>
///
/// </remarks>
/// <param name="body">order placed for purchasing the pet</param>
virtual void place_order(const Order &body, Net::Http::ResponseWriter &response) = 0;
};
}
}
}
}
#endif /* StoreApi_H_ */

View File

@ -0,0 +1,186 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
#include "UserApi.h"
namespace io {
namespace swagger {
namespace server {
namespace api {
using namespace io::swagger::server::model;
UserApi::UserApi(Net::Address addr)
: httpEndpoint(std::make_shared<Net::Http::Endpoint>(addr))
{ };
void UserApi::init(size_t thr = 2) {
auto opts = Net::Http::Endpoint::options()
.threads(thr)
.flags(Net::Tcp::Options::InstallSignalHandler);
httpEndpoint->init(opts);
setupRoutes();
}
void UserApi::start() {
httpEndpoint->setHandler(router.handler());
httpEndpoint->serve();
}
void UserApi::shutdown() {
httpEndpoint->shutdown();
}
void UserApi::setupRoutes() {
using namespace Net::Rest;
Routes::Post(router, base + "/user", Routes::bind(&UserApi::create_user_handler, this));
Routes::Post(router, base + "/user/createWithArray", Routes::bind(&UserApi::create_users_with_array_input_handler, this));
Routes::Post(router, base + "/user/createWithList", Routes::bind(&UserApi::create_users_with_list_input_handler, this));
Routes::Delete(router, base + "/user/:username", Routes::bind(&UserApi::delete_user_handler, this));
Routes::Get(router, base + "/user/:username", Routes::bind(&UserApi::get_user_by_name_handler, this));
Routes::Get(router, base + "/user/login", Routes::bind(&UserApi::login_user_handler, this));
Routes::Get(router, base + "/user/logout", Routes::bind(&UserApi::logout_user_handler, this));
Routes::Put(router, base + "/user/:username", Routes::bind(&UserApi::update_user_handler, this));
// Default handler, called when a route is not found
router.addCustomHandler(Routes::bind(&UserApi::user_api_default_handler, this));
}
void UserApi::create_user_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response) {
// Getting the body param
User body;
try {
nlohmann::json request_body = nlohmann::json::parse(request.body());
body.fromJson(request_body);
this->create_user(body, response);
} catch (std::runtime_error & e) {
//send a 400 error
response.send(Net::Http::Code::Bad_Request, e.what());
return;
}
}
void UserApi::create_users_with_array_input_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response) {
// Getting the body param
User body;
try {
nlohmann::json request_body = nlohmann::json::parse(request.body());
body.fromJson(request_body);
this->create_users_with_array_input(body, response);
} catch (std::runtime_error & e) {
//send a 400 error
response.send(Net::Http::Code::Bad_Request, e.what());
return;
}
}
void UserApi::create_users_with_list_input_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response) {
// Getting the body param
User body;
try {
nlohmann::json request_body = nlohmann::json::parse(request.body());
body.fromJson(request_body);
this->create_users_with_list_input(body, response);
} catch (std::runtime_error & e) {
//send a 400 error
response.send(Net::Http::Code::Bad_Request, e.what());
return;
}
}
void UserApi::delete_user_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response) {
// Getting the path params
auto username = request.param(":username").as<std::string>();
try {
this->delete_user(username, response);
} catch (std::runtime_error & e) {
//send a 400 error
response.send(Net::Http::Code::Bad_Request, e.what());
return;
}
}
void UserApi::get_user_by_name_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response) {
// Getting the path params
auto username = request.param(":username").as<std::string>();
try {
this->get_user_by_name(username, response);
} catch (std::runtime_error & e) {
//send a 400 error
response.send(Net::Http::Code::Bad_Request, e.what());
return;
}
}
void UserApi::login_user_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response) {
// Getting the query params
auto username = request.query().get("username");
auto password = request.query().get("password");
try {
this->login_user(username, password, response);
} catch (std::runtime_error & e) {
//send a 400 error
response.send(Net::Http::Code::Bad_Request, e.what());
return;
}
}
void UserApi::logout_user_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response) {
try {
this->logout_user(response);
} catch (std::runtime_error & e) {
//send a 400 error
response.send(Net::Http::Code::Bad_Request, e.what());
return;
}
}
void UserApi::update_user_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response) {
// Getting the path params
auto username = request.param(":username").as<std::string>();
// Getting the body param
User body;
try {
nlohmann::json request_body = nlohmann::json::parse(request.body());
body.fromJson(request_body);
this->update_user(username, body, response);
} catch (std::runtime_error & e) {
//send a 400 error
response.send(Net::Http::Code::Bad_Request, e.what());
return;
}
}
void UserApi::user_api_default_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response) {
response.send(Net::Http::Code::Not_Found, "The requested method does not exist");
}
}
}
}
}

View File

@ -0,0 +1,146 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/*
* UserApi.h
*
*
*/
#ifndef UserApi_H_
#define UserApi_H_
#include <pistache/endpoint.h>
#include <pistache/http.h>
#include <pistache/router.h>
#include <pistache/http_headers.h>
#include "User.h"
#include <string>
#include <vector>
namespace io {
namespace swagger {
namespace server {
namespace api {
using namespace io::swagger::server::model;
class UserApi {
public:
UserApi(Net::Address addr);
virtual ~UserApi() {};
void init(size_t thr);
void start();
void shutdown();
const std::string base = "/v2";
private:
void setupRoutes();
void create_user_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response);
void create_users_with_array_input_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response);
void create_users_with_list_input_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response);
void delete_user_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response);
void get_user_by_name_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response);
void login_user_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response);
void logout_user_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response);
void update_user_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response);
void user_api_default_handler(const Net::Rest::Request &request, Net::Http::ResponseWriter response);
std::shared_ptr<Net::Http::Endpoint> httpEndpoint;
Net::Rest::Router router;
/// <summary>
/// Create user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name="body">Created user object</param>
virtual void create_user(const User &body, Net::Http::ResponseWriter &response) = 0;
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <remarks>
///
/// </remarks>
/// <param name="body">List of user object</param>
virtual void create_users_with_array_input(const User &body, Net::Http::ResponseWriter &response) = 0;
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <remarks>
///
/// </remarks>
/// <param name="body">List of user object</param>
virtual void create_users_with_list_input(const User &body, Net::Http::ResponseWriter &response) = 0;
/// <summary>
/// Delete user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name="username">The name that needs to be deleted</param>
virtual void delete_user(const std::string &username, Net::Http::ResponseWriter &response) = 0;
/// <summary>
/// Get user by user name
/// </summary>
/// <remarks>
///
/// </remarks>
/// <param name="username">The name that needs to be fetched. Use user1 for testing. </param>
virtual void get_user_by_name(const std::string &username, Net::Http::ResponseWriter &response) = 0;
/// <summary>
/// Logs user into the system
/// </summary>
/// <remarks>
///
/// </remarks>
/// <param name="username">The user name for login</param>
/// <param name="password">The password for login in clear text</param>
virtual void login_user(const Optional<std::string> &username, const Optional<std::string> &password, Net::Http::ResponseWriter &response) = 0;
/// <summary>
/// Logs out current logged in user session
/// </summary>
/// <remarks>
///
/// </remarks>
virtual void logout_user(Net::Http::ResponseWriter &response) = 0;
/// <summary>
/// Updated user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name="username">name that need to be deleted</param>
/// <param name="body">Updated user object</param>
virtual void update_user(const std::string &username, const User &body, Net::Http::ResponseWriter &response) = 0;
};
}
}
}
}
#endif /* UserApi_H_ */

View File

@ -0,0 +1,55 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
#include "PetApiImpl.h"
namespace io {
namespace swagger {
namespace server {
namespace api {
using namespace io::swagger::server::model;
PetApiImpl::PetApiImpl(Net::Address addr)
: PetApi(addr)
{ }
void PetApiImpl::add_pet(const Pet &body, Net::Http::ResponseWriter &response) {
response.send(Net::Http::Code::Ok, "Do some magic\n");
}
void PetApiImpl::delete_pet(const int64_t &petId, const Optional<Net::Http::Header::Raw> &apiKey, Net::Http::ResponseWriter &response) {
response.send(Net::Http::Code::Ok, "Do some magic\n");
}
void PetApiImpl::find_pets_by_status(const Optional<std::string> &status, Net::Http::ResponseWriter &response) {
response.send(Net::Http::Code::Ok, "Do some magic\n");
}
void PetApiImpl::find_pets_by_tags(const Optional<std::string> &tags, Net::Http::ResponseWriter &response) {
response.send(Net::Http::Code::Ok, "Do some magic\n");
}
void PetApiImpl::get_pet_by_id(const int64_t &petId, Net::Http::ResponseWriter &response) {
response.send(Net::Http::Code::Ok, "Do some magic\n");
}
void PetApiImpl::update_pet(const Pet &body, Net::Http::ResponseWriter &response) {
response.send(Net::Http::Code::Ok, "Do some magic\n");
}
void PetApiImpl::update_pet_with_form(const Net::Rest::Request &request, Net::Http::ResponseWriter &response){
response.send(Net::Http::Code::Ok, "Do some magic\n");
}
void PetApiImpl::upload_file(const Net::Rest::Request &request, Net::Http::ResponseWriter &response){
response.send(Net::Http::Code::Ok, "Do some magic\n");
}
}
}
}
}

View File

@ -0,0 +1,64 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/*
* PetApiImpl.h
*
*
*/
#ifndef PET_API_IMPL_H_
#define PET_API_IMPL_H_
#include <pistache/endpoint.h>
#include <pistache/http.h>
#include <pistache/router.h>
#include <memory>
#include <PetApi.h>
#include "ApiResponse.h"
#include "Pet.h"
#include <string>
namespace io {
namespace swagger {
namespace server {
namespace api {
using namespace io::swagger::server::model;
class PetApiImpl : public io::swagger::server::api::PetApi {
public:
PetApiImpl(Net::Address addr);
~PetApiImpl() { };
void add_pet(const Pet &body, Net::Http::ResponseWriter &response);
void delete_pet(const int64_t &petId, const Optional<Net::Http::Header::Raw> &apiKey, Net::Http::ResponseWriter &response);
void find_pets_by_status(const Optional<std::string> &status, Net::Http::ResponseWriter &response);
void find_pets_by_tags(const Optional<std::string> &tags, Net::Http::ResponseWriter &response);
void get_pet_by_id(const int64_t &petId, Net::Http::ResponseWriter &response);
void update_pet(const Pet &body, Net::Http::ResponseWriter &response);
void update_pet_with_form(const Net::Rest::Request &request, Net::Http::ResponseWriter &response);
void upload_file(const Net::Rest::Request &request, Net::Http::ResponseWriter &response);
};
}
}
}
}
#endif

View File

@ -0,0 +1,43 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
#include "StoreApiImpl.h"
namespace io {
namespace swagger {
namespace server {
namespace api {
using namespace io::swagger::server::model;
StoreApiImpl::StoreApiImpl(Net::Address addr)
: StoreApi(addr)
{ }
void StoreApiImpl::delete_order(const std::string &orderId, Net::Http::ResponseWriter &response) {
response.send(Net::Http::Code::Ok, "Do some magic\n");
}
void StoreApiImpl::get_inventory(Net::Http::ResponseWriter &response) {
response.send(Net::Http::Code::Ok, "Do some magic\n");
}
void StoreApiImpl::get_order_by_id(const int64_t &orderId, Net::Http::ResponseWriter &response) {
response.send(Net::Http::Code::Ok, "Do some magic\n");
}
void StoreApiImpl::place_order(const Order &body, Net::Http::ResponseWriter &response) {
response.send(Net::Http::Code::Ok, "Do some magic\n");
}
}
}
}
}

View File

@ -0,0 +1,60 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/*
* StoreApiImpl.h
*
*
*/
#ifndef STORE_API_IMPL_H_
#define STORE_API_IMPL_H_
#include <pistache/endpoint.h>
#include <pistache/http.h>
#include <pistache/router.h>
#include <memory>
#include <StoreApi.h>
#include "Order.h"
#include <map>
#include <string>
namespace io {
namespace swagger {
namespace server {
namespace api {
using namespace io::swagger::server::model;
class StoreApiImpl : public io::swagger::server::api::StoreApi {
public:
StoreApiImpl(Net::Address addr);
~StoreApiImpl() { };
void delete_order(const std::string &orderId, Net::Http::ResponseWriter &response);
void get_inventory(Net::Http::ResponseWriter &response);
void get_order_by_id(const int64_t &orderId, Net::Http::ResponseWriter &response);
void place_order(const Order &body, Net::Http::ResponseWriter &response);
};
}
}
}
}
#endif

View File

@ -0,0 +1,55 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
#include "UserApiImpl.h"
namespace io {
namespace swagger {
namespace server {
namespace api {
using namespace io::swagger::server::model;
UserApiImpl::UserApiImpl(Net::Address addr)
: UserApi(addr)
{ }
void UserApiImpl::create_user(const User &body, Net::Http::ResponseWriter &response) {
response.send(Net::Http::Code::Ok, "Do some magic\n");
}
void UserApiImpl::create_users_with_array_input(const User &body, Net::Http::ResponseWriter &response) {
response.send(Net::Http::Code::Ok, "Do some magic\n");
}
void UserApiImpl::create_users_with_list_input(const User &body, Net::Http::ResponseWriter &response) {
response.send(Net::Http::Code::Ok, "Do some magic\n");
}
void UserApiImpl::delete_user(const std::string &username, Net::Http::ResponseWriter &response) {
response.send(Net::Http::Code::Ok, "Do some magic\n");
}
void UserApiImpl::get_user_by_name(const std::string &username, Net::Http::ResponseWriter &response) {
response.send(Net::Http::Code::Ok, "Do some magic\n");
}
void UserApiImpl::login_user(const Optional<std::string> &username, const Optional<std::string> &password, Net::Http::ResponseWriter &response) {
response.send(Net::Http::Code::Ok, "Do some magic\n");
}
void UserApiImpl::logout_user(Net::Http::ResponseWriter &response) {
response.send(Net::Http::Code::Ok, "Do some magic\n");
}
void UserApiImpl::update_user(const std::string &username, const User &body, Net::Http::ResponseWriter &response) {
response.send(Net::Http::Code::Ok, "Do some magic\n");
}
}
}
}
}

View File

@ -0,0 +1,64 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/*
* UserApiImpl.h
*
*
*/
#ifndef USER_API_IMPL_H_
#define USER_API_IMPL_H_
#include <pistache/endpoint.h>
#include <pistache/http.h>
#include <pistache/router.h>
#include <memory>
#include <UserApi.h>
#include "User.h"
#include <string>
#include <vector>
namespace io {
namespace swagger {
namespace server {
namespace api {
using namespace io::swagger::server::model;
class UserApiImpl : public io::swagger::server::api::UserApi {
public:
UserApiImpl(Net::Address addr);
~UserApiImpl() { };
void create_user(const User &body, Net::Http::ResponseWriter &response);
void create_users_with_array_input(const User &body, Net::Http::ResponseWriter &response);
void create_users_with_list_input(const User &body, Net::Http::ResponseWriter &response);
void delete_user(const std::string &username, Net::Http::ResponseWriter &response);
void get_user_by_name(const std::string &username, Net::Http::ResponseWriter &response);
void login_user(const Optional<std::string> &username, const Optional<std::string> &password, Net::Http::ResponseWriter &response);
void logout_user(Net::Http::ResponseWriter &response);
void update_user(const std::string &username, const User &body, Net::Http::ResponseWriter &response);
};
}
}
}
}
#endif

View File

@ -0,0 +1,138 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
#include "ApiResponse.h"
namespace io {
namespace swagger {
namespace server {
namespace model {
ApiResponse::ApiResponse()
{
m_Code = 0;
m_CodeIsSet = false;
m_Type = "";
m_TypeIsSet = false;
m_Message = "";
m_MessageIsSet = false;
}
ApiResponse::~ApiResponse()
{
}
void ApiResponse::validate()
{
// TODO: implement validation
}
nlohmann::json ApiResponse::toJson() const
{
nlohmann::json val = nlohmann::json::object();
if(m_CodeIsSet)
{
val["code"] = m_Code;
}
if(m_TypeIsSet)
{
val["type"] = ModelBase::toJson(m_Type);
}
if(m_MessageIsSet)
{
val["message"] = ModelBase::toJson(m_Message);
}
return val;
}
void ApiResponse::fromJson(nlohmann::json& val)
{
if(val.find("code") != val.end())
{
setCode(val.at("code"));
}
if(val.find("type") != val.end())
{
setType(val.at("type"));
}
if(val.find("message") != val.end())
{
setMessage(val.at("message"));
}
}
int32_t ApiResponse::getCode() const
{
return m_Code;
}
void ApiResponse::setCode(int32_t value)
{
m_Code = value;
m_CodeIsSet = true;
}
bool ApiResponse::codeIsSet() const
{
return m_CodeIsSet;
}
void ApiResponse::unsetCode()
{
m_CodeIsSet = false;
}
std::string ApiResponse::getType() const
{
return m_Type;
}
void ApiResponse::setType(std::string value)
{
m_Type = value;
m_TypeIsSet = true;
}
bool ApiResponse::typeIsSet() const
{
return m_TypeIsSet;
}
void ApiResponse::unsetType()
{
m_TypeIsSet = false;
}
std::string ApiResponse::getMessage() const
{
return m_Message;
}
void ApiResponse::setMessage(std::string value)
{
m_Message = value;
m_MessageIsSet = true;
}
bool ApiResponse::messageIsSet() const
{
return m_MessageIsSet;
}
void ApiResponse::unsetMessage()
{
m_MessageIsSet = false;
}
}
}
}
}

View File

@ -0,0 +1,88 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/*
* ApiResponse.h
*
* Describes the result of uploading an image resource
*/
#ifndef ApiResponse_H_
#define ApiResponse_H_
#include "ModelBase.h"
#include <string>
namespace io {
namespace swagger {
namespace server {
namespace model {
/// <summary>
/// Describes the result of uploading an image resource
/// </summary>
class ApiResponse
: public ModelBase
{
public:
ApiResponse();
virtual ~ApiResponse();
/////////////////////////////////////////////
/// ModelBase overrides
void validate() override;
nlohmann::json toJson() const override;
void fromJson(nlohmann::json& json) override;
/////////////////////////////////////////////
/// ApiResponse members
/// <summary>
///
/// </summary>
int32_t getCode() const;
void setCode(int32_t value);
bool codeIsSet() const;
void unsetCode();
/// <summary>
///
/// </summary>
std::string getType() const;
void setType(std::string value);
bool typeIsSet() const;
void unsetType();
/// <summary>
///
/// </summary>
std::string getMessage() const;
void setMessage(std::string value);
bool messageIsSet() const;
void unsetMessage();
protected:
int32_t m_Code;
bool m_CodeIsSet;
std::string m_Type;
bool m_TypeIsSet;
std::string m_Message;
bool m_MessageIsSet;
};
}
}
}
}
#endif /* ApiResponse_H_ */

View File

@ -0,0 +1,110 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
#include "Category.h"
namespace io {
namespace swagger {
namespace server {
namespace model {
Category::Category()
{
m_Id = 0;
m_IdIsSet = false;
m_Name = "";
m_NameIsSet = false;
}
Category::~Category()
{
}
void Category::validate()
{
// TODO: implement validation
}
nlohmann::json Category::toJson() const
{
nlohmann::json val = nlohmann::json::object();
if(m_IdIsSet)
{
val["id"] = m_Id;
}
if(m_NameIsSet)
{
val["name"] = ModelBase::toJson(m_Name);
}
return val;
}
void Category::fromJson(nlohmann::json& val)
{
if(val.find("id") != val.end())
{
setId(val.at("id"));
}
if(val.find("name") != val.end())
{
setName(val.at("name"));
}
}
int64_t Category::getId() const
{
return m_Id;
}
void Category::setId(int64_t value)
{
m_Id = value;
m_IdIsSet = true;
}
bool Category::idIsSet() const
{
return m_IdIsSet;
}
void Category::unsetId()
{
m_IdIsSet = false;
}
std::string Category::getName() const
{
return m_Name;
}
void Category::setName(std::string value)
{
m_Name = value;
m_NameIsSet = true;
}
bool Category::nameIsSet() const
{
return m_NameIsSet;
}
void Category::unsetName()
{
m_NameIsSet = false;
}
}
}
}
}

View File

@ -0,0 +1,79 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/*
* Category.h
*
* A category for a pet
*/
#ifndef Category_H_
#define Category_H_
#include "ModelBase.h"
#include <string>
namespace io {
namespace swagger {
namespace server {
namespace model {
/// <summary>
/// A category for a pet
/// </summary>
class Category
: public ModelBase
{
public:
Category();
virtual ~Category();
/////////////////////////////////////////////
/// ModelBase overrides
void validate() override;
nlohmann::json toJson() const override;
void fromJson(nlohmann::json& json) override;
/////////////////////////////////////////////
/// Category members
/// <summary>
///
/// </summary>
int64_t getId() const;
void setId(int64_t value);
bool idIsSet() const;
void unsetId();
/// <summary>
///
/// </summary>
std::string getName() const;
void setName(std::string value);
bool nameIsSet() const;
void unsetName();
protected:
int64_t m_Id;
bool m_IdIsSet;
std::string m_Name;
bool m_NameIsSet;
};
}
}
}
}
#endif /* Category_H_ */

View File

@ -0,0 +1,66 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
#include "ModelBase.h"
namespace io {
namespace swagger {
namespace server {
namespace model {
ModelBase::ModelBase()
{
}
ModelBase::~ModelBase()
{
}
std::string ModelBase::toJson( const std::string& value )
{
return value;
}
std::string ModelBase::toJson( const std::time_t& value )
{
char buf[sizeof "2011-10-08T07:07:09Z"];
strftime(buf, sizeof buf, "%FT%TZ", gmtime(&value));
return buf;
}
int32_t ModelBase::toJson( int32_t value )
{
return value;
}
int64_t ModelBase::toJson( int64_t value )
{
return value;
}
double ModelBase::toJson( double value )
{
return value;
}
bool ModelBase::toJson( bool value )
{
return value;
}
nlohmann::json ModelBase::toJson( std::shared_ptr<ModelBase> content )
{
return content.get() ? content->toJson() : nlohmann::json();
}
}
}
}
}

View File

@ -0,0 +1,57 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/*
* ModelBase.h
*
* This is the base class for all model classes
*/
#ifndef ModelBase_H_
#define ModelBase_H_
#include "json.hpp"
#include <ctime>
#include <string>
namespace io {
namespace swagger {
namespace server {
namespace model {
class ModelBase
{
public:
ModelBase();
virtual ~ModelBase();
virtual void validate() = 0;
virtual nlohmann::json toJson() const = 0;
virtual void fromJson(nlohmann::json& json) = 0;
static std::string toJson( const std::string& value );
static std::string toJson( const std::time_t& value );
static int32_t toJson( int32_t value );
static int64_t toJson( int64_t value );
static double toJson( double value );
static bool toJson( bool value );
static nlohmann::json toJson( std::shared_ptr<ModelBase> content );
};
}
}
}
}
#endif /* ModelBase_H_ */

View File

@ -0,0 +1,219 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
#include "Order.h"
namespace io {
namespace swagger {
namespace server {
namespace model {
Order::Order()
{
m_Id = 0;
m_IdIsSet = false;
m_PetId = 0;
m_PetIdIsSet = false;
m_Quantity = 0;
m_QuantityIsSet = false;
m_ShipDate = "";
m_ShipDateIsSet = false;
m_Status = "";
m_StatusIsSet = false;
m_Complete = false;
m_CompleteIsSet = false;
}
Order::~Order()
{
}
void Order::validate()
{
// TODO: implement validation
}
nlohmann::json Order::toJson() const
{
nlohmann::json val = nlohmann::json::object();
if(m_IdIsSet)
{
val["id"] = m_Id;
}
if(m_PetIdIsSet)
{
val["petId"] = m_PetId;
}
if(m_QuantityIsSet)
{
val["quantity"] = m_Quantity;
}
if(m_ShipDateIsSet)
{
val["shipDate"] = ModelBase::toJson(m_ShipDate);
}
if(m_StatusIsSet)
{
val["status"] = ModelBase::toJson(m_Status);
}
if(m_CompleteIsSet)
{
val["complete"] = m_Complete;
}
return val;
}
void Order::fromJson(nlohmann::json& val)
{
if(val.find("id") != val.end())
{
setId(val.at("id"));
}
if(val.find("petId") != val.end())
{
setPetId(val.at("petId"));
}
if(val.find("quantity") != val.end())
{
setQuantity(val.at("quantity"));
}
if(val.find("shipDate") != val.end())
{
setShipDate(val.at("shipDate"));
}
if(val.find("status") != val.end())
{
setStatus(val.at("status"));
}
if(val.find("complete") != val.end())
{
setComplete(val.at("complete"));
}
}
int64_t Order::getId() const
{
return m_Id;
}
void Order::setId(int64_t value)
{
m_Id = value;
m_IdIsSet = true;
}
bool Order::idIsSet() const
{
return m_IdIsSet;
}
void Order::unsetId()
{
m_IdIsSet = false;
}
int64_t Order::getPetId() const
{
return m_PetId;
}
void Order::setPetId(int64_t value)
{
m_PetId = value;
m_PetIdIsSet = true;
}
bool Order::petIdIsSet() const
{
return m_PetIdIsSet;
}
void Order::unsetPetId()
{
m_PetIdIsSet = false;
}
int32_t Order::getQuantity() const
{
return m_Quantity;
}
void Order::setQuantity(int32_t value)
{
m_Quantity = value;
m_QuantityIsSet = true;
}
bool Order::quantityIsSet() const
{
return m_QuantityIsSet;
}
void Order::unsetQuantity()
{
m_QuantityIsSet = false;
}
std::string Order::getShipDate() const
{
return m_ShipDate;
}
void Order::setShipDate(std::string value)
{
m_ShipDate = value;
m_ShipDateIsSet = true;
}
bool Order::shipDateIsSet() const
{
return m_ShipDateIsSet;
}
void Order::unsetShipDate()
{
m_ShipDateIsSet = false;
}
std::string Order::getStatus() const
{
return m_Status;
}
void Order::setStatus(std::string value)
{
m_Status = value;
m_StatusIsSet = true;
}
bool Order::statusIsSet() const
{
return m_StatusIsSet;
}
void Order::unsetStatus()
{
m_StatusIsSet = false;
}
bool Order::getComplete() const
{
return m_Complete;
}
void Order::setComplete(bool value)
{
m_Complete = value;
m_CompleteIsSet = true;
}
bool Order::completeIsSet() const
{
return m_CompleteIsSet;
}
void Order::unsetComplete()
{
m_CompleteIsSet = false;
}
}
}
}
}

View File

@ -0,0 +1,115 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/*
* Order.h
*
* An order for a pets from the pet store
*/
#ifndef Order_H_
#define Order_H_
#include "ModelBase.h"
#include <string>
namespace io {
namespace swagger {
namespace server {
namespace model {
/// <summary>
/// An order for a pets from the pet store
/// </summary>
class Order
: public ModelBase
{
public:
Order();
virtual ~Order();
/////////////////////////////////////////////
/// ModelBase overrides
void validate() override;
nlohmann::json toJson() const override;
void fromJson(nlohmann::json& json) override;
/////////////////////////////////////////////
/// Order members
/// <summary>
///
/// </summary>
int64_t getId() const;
void setId(int64_t value);
bool idIsSet() const;
void unsetId();
/// <summary>
///
/// </summary>
int64_t getPetId() const;
void setPetId(int64_t value);
bool petIdIsSet() const;
void unsetPetId();
/// <summary>
///
/// </summary>
int32_t getQuantity() const;
void setQuantity(int32_t value);
bool quantityIsSet() const;
void unsetQuantity();
/// <summary>
///
/// </summary>
std::string getShipDate() const;
void setShipDate(std::string value);
bool shipDateIsSet() const;
void unsetShipDate();
/// <summary>
/// Order Status
/// </summary>
std::string getStatus() const;
void setStatus(std::string value);
bool statusIsSet() const;
void unsetStatus();
/// <summary>
///
/// </summary>
bool getComplete() const;
void setComplete(bool value);
bool completeIsSet() const;
void unsetComplete();
protected:
int64_t m_Id;
bool m_IdIsSet;
int64_t m_PetId;
bool m_PetIdIsSet;
int32_t m_Quantity;
bool m_QuantityIsSet;
std::string m_ShipDate;
bool m_ShipDateIsSet;
std::string m_Status;
bool m_StatusIsSet;
bool m_Complete;
bool m_CompleteIsSet;
};
}
}
}
}
#endif /* Order_H_ */

View File

@ -0,0 +1,222 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
#include "Pet.h"
namespace io {
namespace swagger {
namespace server {
namespace model {
Pet::Pet()
{
m_Id = 0;
m_IdIsSet = false;
m_CategoryIsSet = false;
m_Name = "";
m_TagsIsSet = false;
m_Status = "";
m_StatusIsSet = false;
}
Pet::~Pet()
{
}
void Pet::validate()
{
// TODO: implement validation
}
nlohmann::json Pet::toJson() const
{
nlohmann::json val = nlohmann::json::object();
if(m_IdIsSet)
{
val["id"] = m_Id;
}
if(m_CategoryIsSet)
{
val["category"] = ModelBase::toJson(m_Category);
}
val["name"] = ModelBase::toJson(m_Name);
{
nlohmann::json jsonArray;
for( auto& item : m_PhotoUrls )
{
jsonArray.push_back(ModelBase::toJson(item));
}
val["photoUrls"] = jsonArray;
}
{
nlohmann::json jsonArray;
for( auto& item : m_Tags )
{
jsonArray.push_back(ModelBase::toJson(item));
}
if(jsonArray.size() > 0)
{
val["tags"] = jsonArray;
}
}
if(m_StatusIsSet)
{
val["status"] = ModelBase::toJson(m_Status);
}
return val;
}
void Pet::fromJson(nlohmann::json& val)
{
if(val.find("id") != val.end())
{
setId(val.at("id"));
}
if(val.find("category") != val.end())
{
if(!val["category"].is_null())
{
std::shared_ptr<Category> newItem(new Category());
newItem->fromJson(val["category"]);
setCategory( newItem );
}
}
setName(val.at("name"));
{
m_PhotoUrls.clear();
nlohmann::json jsonArray;
for( auto& item : val["photoUrls"] )
{
m_PhotoUrls.push_back(item);
}
}
{
m_Tags.clear();
nlohmann::json jsonArray;
if(val.find("tags") != val.end())
{
for( auto& item : val["tags"] )
{
if(item.is_null())
{
m_Tags.push_back( std::shared_ptr<Tag>(nullptr) );
}
else
{
std::shared_ptr<Tag> newItem(new Tag());
newItem->fromJson(item);
m_Tags.push_back( newItem );
}
}
}
}
if(val.find("status") != val.end())
{
setStatus(val.at("status"));
}
}
int64_t Pet::getId() const
{
return m_Id;
}
void Pet::setId(int64_t value)
{
m_Id = value;
m_IdIsSet = true;
}
bool Pet::idIsSet() const
{
return m_IdIsSet;
}
void Pet::unsetId()
{
m_IdIsSet = false;
}
std::shared_ptr<Category> Pet::getCategory() const
{
return m_Category;
}
void Pet::setCategory(std::shared_ptr<Category> value)
{
m_Category = value;
m_CategoryIsSet = true;
}
bool Pet::categoryIsSet() const
{
return m_CategoryIsSet;
}
void Pet::unsetCategory()
{
m_CategoryIsSet = false;
}
std::string Pet::getName() const
{
return m_Name;
}
void Pet::setName(std::string value)
{
m_Name = value;
}
std::vector<std::string>& Pet::getPhotoUrls()
{
return m_PhotoUrls;
}
std::vector<std::shared_ptr<Tag>>& Pet::getTags()
{
return m_Tags;
}
bool Pet::tagsIsSet() const
{
return m_TagsIsSet;
}
void Pet::unsetTags()
{
m_TagsIsSet = false;
}
std::string Pet::getStatus() const
{
return m_Status;
}
void Pet::setStatus(std::string value)
{
m_Status = value;
m_StatusIsSet = true;
}
bool Pet::statusIsSet() const
{
return m_StatusIsSet;
}
void Pet::unsetStatus()
{
m_StatusIsSet = false;
}
}
}
}
}

View File

@ -0,0 +1,112 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/*
* Pet.h
*
* A pet for sale in the pet store
*/
#ifndef Pet_H_
#define Pet_H_
#include "ModelBase.h"
#include "Tag.h"
#include <string>
#include "Category.h"
#include <vector>
namespace io {
namespace swagger {
namespace server {
namespace model {
/// <summary>
/// A pet for sale in the pet store
/// </summary>
class Pet
: public ModelBase
{
public:
Pet();
virtual ~Pet();
/////////////////////////////////////////////
/// ModelBase overrides
void validate() override;
nlohmann::json toJson() const override;
void fromJson(nlohmann::json& json) override;
/////////////////////////////////////////////
/// Pet members
/// <summary>
///
/// </summary>
int64_t getId() const;
void setId(int64_t value);
bool idIsSet() const;
void unsetId();
/// <summary>
///
/// </summary>
std::shared_ptr<Category> getCategory() const;
void setCategory(std::shared_ptr<Category> value);
bool categoryIsSet() const;
void unsetCategory();
/// <summary>
///
/// </summary>
std::string getName() const;
void setName(std::string value);
/// <summary>
///
/// </summary>
std::vector<std::string>& getPhotoUrls();
/// <summary>
///
/// </summary>
std::vector<std::shared_ptr<Tag>>& getTags();
bool tagsIsSet() const;
void unsetTags();
/// <summary>
/// pet status in the store
/// </summary>
std::string getStatus() const;
void setStatus(std::string value);
bool statusIsSet() const;
void unsetStatus();
protected:
int64_t m_Id;
bool m_IdIsSet;
std::shared_ptr<Category> m_Category;
bool m_CategoryIsSet;
std::string m_Name;
std::vector<std::string> m_PhotoUrls;
std::vector<std::shared_ptr<Tag>> m_Tags;
bool m_TagsIsSet;
std::string m_Status;
bool m_StatusIsSet;
};
}
}
}
}
#endif /* Pet_H_ */

View File

@ -0,0 +1,110 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
#include "Tag.h"
namespace io {
namespace swagger {
namespace server {
namespace model {
Tag::Tag()
{
m_Id = 0;
m_IdIsSet = false;
m_Name = "";
m_NameIsSet = false;
}
Tag::~Tag()
{
}
void Tag::validate()
{
// TODO: implement validation
}
nlohmann::json Tag::toJson() const
{
nlohmann::json val = nlohmann::json::object();
if(m_IdIsSet)
{
val["id"] = m_Id;
}
if(m_NameIsSet)
{
val["name"] = ModelBase::toJson(m_Name);
}
return val;
}
void Tag::fromJson(nlohmann::json& val)
{
if(val.find("id") != val.end())
{
setId(val.at("id"));
}
if(val.find("name") != val.end())
{
setName(val.at("name"));
}
}
int64_t Tag::getId() const
{
return m_Id;
}
void Tag::setId(int64_t value)
{
m_Id = value;
m_IdIsSet = true;
}
bool Tag::idIsSet() const
{
return m_IdIsSet;
}
void Tag::unsetId()
{
m_IdIsSet = false;
}
std::string Tag::getName() const
{
return m_Name;
}
void Tag::setName(std::string value)
{
m_Name = value;
m_NameIsSet = true;
}
bool Tag::nameIsSet() const
{
return m_NameIsSet;
}
void Tag::unsetName()
{
m_NameIsSet = false;
}
}
}
}
}

View File

@ -0,0 +1,79 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/*
* Tag.h
*
* A tag for a pet
*/
#ifndef Tag_H_
#define Tag_H_
#include "ModelBase.h"
#include <string>
namespace io {
namespace swagger {
namespace server {
namespace model {
/// <summary>
/// A tag for a pet
/// </summary>
class Tag
: public ModelBase
{
public:
Tag();
virtual ~Tag();
/////////////////////////////////////////////
/// ModelBase overrides
void validate() override;
nlohmann::json toJson() const override;
void fromJson(nlohmann::json& json) override;
/////////////////////////////////////////////
/// Tag members
/// <summary>
///
/// </summary>
int64_t getId() const;
void setId(int64_t value);
bool idIsSet() const;
void unsetId();
/// <summary>
///
/// </summary>
std::string getName() const;
void setName(std::string value);
bool nameIsSet() const;
void unsetName();
protected:
int64_t m_Id;
bool m_IdIsSet;
std::string m_Name;
bool m_NameIsSet;
};
}
}
}
}
#endif /* Tag_H_ */

View File

@ -0,0 +1,277 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
#include "User.h"
namespace io {
namespace swagger {
namespace server {
namespace model {
User::User()
{
m_Id = 0;
m_IdIsSet = false;
m_Username = "";
m_UsernameIsSet = false;
m_FirstName = "";
m_FirstNameIsSet = false;
m_LastName = "";
m_LastNameIsSet = false;
m_Email = "";
m_EmailIsSet = false;
m_Password = "";
m_PasswordIsSet = false;
m_Phone = "";
m_PhoneIsSet = false;
m_UserStatus = 0;
m_UserStatusIsSet = false;
}
User::~User()
{
}
void User::validate()
{
// TODO: implement validation
}
nlohmann::json User::toJson() const
{
nlohmann::json val = nlohmann::json::object();
if(m_IdIsSet)
{
val["id"] = m_Id;
}
if(m_UsernameIsSet)
{
val["username"] = ModelBase::toJson(m_Username);
}
if(m_FirstNameIsSet)
{
val["firstName"] = ModelBase::toJson(m_FirstName);
}
if(m_LastNameIsSet)
{
val["lastName"] = ModelBase::toJson(m_LastName);
}
if(m_EmailIsSet)
{
val["email"] = ModelBase::toJson(m_Email);
}
if(m_PasswordIsSet)
{
val["password"] = ModelBase::toJson(m_Password);
}
if(m_PhoneIsSet)
{
val["phone"] = ModelBase::toJson(m_Phone);
}
if(m_UserStatusIsSet)
{
val["userStatus"] = m_UserStatus;
}
return val;
}
void User::fromJson(nlohmann::json& val)
{
if(val.find("id") != val.end())
{
setId(val.at("id"));
}
if(val.find("username") != val.end())
{
setUsername(val.at("username"));
}
if(val.find("firstName") != val.end())
{
setFirstName(val.at("firstName"));
}
if(val.find("lastName") != val.end())
{
setLastName(val.at("lastName"));
}
if(val.find("email") != val.end())
{
setEmail(val.at("email"));
}
if(val.find("password") != val.end())
{
setPassword(val.at("password"));
}
if(val.find("phone") != val.end())
{
setPhone(val.at("phone"));
}
if(val.find("userStatus") != val.end())
{
setUserStatus(val.at("userStatus"));
}
}
int64_t User::getId() const
{
return m_Id;
}
void User::setId(int64_t value)
{
m_Id = value;
m_IdIsSet = true;
}
bool User::idIsSet() const
{
return m_IdIsSet;
}
void User::unsetId()
{
m_IdIsSet = false;
}
std::string User::getUsername() const
{
return m_Username;
}
void User::setUsername(std::string value)
{
m_Username = value;
m_UsernameIsSet = true;
}
bool User::usernameIsSet() const
{
return m_UsernameIsSet;
}
void User::unsetUsername()
{
m_UsernameIsSet = false;
}
std::string User::getFirstName() const
{
return m_FirstName;
}
void User::setFirstName(std::string value)
{
m_FirstName = value;
m_FirstNameIsSet = true;
}
bool User::firstNameIsSet() const
{
return m_FirstNameIsSet;
}
void User::unsetFirstName()
{
m_FirstNameIsSet = false;
}
std::string User::getLastName() const
{
return m_LastName;
}
void User::setLastName(std::string value)
{
m_LastName = value;
m_LastNameIsSet = true;
}
bool User::lastNameIsSet() const
{
return m_LastNameIsSet;
}
void User::unsetLastName()
{
m_LastNameIsSet = false;
}
std::string User::getEmail() const
{
return m_Email;
}
void User::setEmail(std::string value)
{
m_Email = value;
m_EmailIsSet = true;
}
bool User::emailIsSet() const
{
return m_EmailIsSet;
}
void User::unsetEmail()
{
m_EmailIsSet = false;
}
std::string User::getPassword() const
{
return m_Password;
}
void User::setPassword(std::string value)
{
m_Password = value;
m_PasswordIsSet = true;
}
bool User::passwordIsSet() const
{
return m_PasswordIsSet;
}
void User::unsetPassword()
{
m_PasswordIsSet = false;
}
std::string User::getPhone() const
{
return m_Phone;
}
void User::setPhone(std::string value)
{
m_Phone = value;
m_PhoneIsSet = true;
}
bool User::phoneIsSet() const
{
return m_PhoneIsSet;
}
void User::unsetPhone()
{
m_PhoneIsSet = false;
}
int32_t User::getUserStatus() const
{
return m_UserStatus;
}
void User::setUserStatus(int32_t value)
{
m_UserStatus = value;
m_UserStatusIsSet = true;
}
bool User::userStatusIsSet() const
{
return m_UserStatusIsSet;
}
void User::unsetUserStatus()
{
m_UserStatusIsSet = false;
}
}
}
}
}

View File

@ -0,0 +1,133 @@
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
/*
* User.h
*
* A User who is purchasing from the pet store
*/
#ifndef User_H_
#define User_H_
#include "ModelBase.h"
#include <string>
namespace io {
namespace swagger {
namespace server {
namespace model {
/// <summary>
/// A User who is purchasing from the pet store
/// </summary>
class User
: public ModelBase
{
public:
User();
virtual ~User();
/////////////////////////////////////////////
/// ModelBase overrides
void validate() override;
nlohmann::json toJson() const override;
void fromJson(nlohmann::json& json) override;
/////////////////////////////////////////////
/// User members
/// <summary>
///
/// </summary>
int64_t getId() const;
void setId(int64_t value);
bool idIsSet() const;
void unsetId();
/// <summary>
///
/// </summary>
std::string getUsername() const;
void setUsername(std::string value);
bool usernameIsSet() const;
void unsetUsername();
/// <summary>
///
/// </summary>
std::string getFirstName() const;
void setFirstName(std::string value);
bool firstNameIsSet() const;
void unsetFirstName();
/// <summary>
///
/// </summary>
std::string getLastName() const;
void setLastName(std::string value);
bool lastNameIsSet() const;
void unsetLastName();
/// <summary>
///
/// </summary>
std::string getEmail() const;
void setEmail(std::string value);
bool emailIsSet() const;
void unsetEmail();
/// <summary>
///
/// </summary>
std::string getPassword() const;
void setPassword(std::string value);
bool passwordIsSet() const;
void unsetPassword();
/// <summary>
///
/// </summary>
std::string getPhone() const;
void setPhone(std::string value);
bool phoneIsSet() const;
void unsetPhone();
/// <summary>
/// User Status
/// </summary>
int32_t getUserStatus() const;
void setUserStatus(int32_t value);
bool userStatusIsSet() const;
void unsetUserStatus();
protected:
int64_t m_Id;
bool m_IdIsSet;
std::string m_Username;
bool m_UsernameIsSet;
std::string m_FirstName;
bool m_FirstNameIsSet;
std::string m_LastName;
bool m_LastNameIsSet;
std::string m_Email;
bool m_EmailIsSet;
std::string m_Password;
bool m_PasswordIsSet;
std::string m_Phone;
bool m_PhoneIsSet;
int32_t m_UserStatus;
bool m_UserStatusIsSet;
};
}
}
}
}
#endif /* User_H_ */