[rust-server] (Re-)Adding support for rust-server (#290)

* First attempt at getting rust-server working

* Solve the problem of spurious 'object's

* We've found the missing models

* Catch some single-var objects correctly

* Get single-param models 'working'

* Got files working

* Remove surplus logging

* Disable some things to get it compiling

* `cargo test` now passes as well

* Create rust-server-specific petstore.yaml

We've commented out a few bits that rust-server doesn't yet support

* Remove commented-out code

And finally get rid of the generation date in the sample
This commit is contained in:
Benjamin Gill
2018-06-13 11:53:03 +01:00
committed by William Cheng
parent 49b8ece776
commit 6f6a4a1013
22 changed files with 4192 additions and 3309 deletions

View File

@@ -27,6 +27,6 @@ fi
# if you've executed sbt assembly previously it will use that instead. # 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" export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/rust-server -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g rust-server -o samples/server/petstore/rust-server -DpackageName=petstore_api $@" ags="generate -t modules/openapi-generator/src/main/resources/rust-server -i modules/openapi-generator/src/test/resources/2_0/rust-server/petstore-with-fake-endpoints-models-for-testing.yaml -g rust-server -o samples/server/petstore/rust-server -DpackageName=petstore_api --additional-properties hideGenerationTimestamp=true $@"
java $JAVA_OPTS -jar $executable $ags java $JAVA_OPTS -jar $executable $ags

View File

@@ -77,6 +77,9 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
public RustServerCodegen() { public RustServerCodegen() {
super(); super();
// Show the generation timestamp by default
hideGenerationTimestamp = Boolean.FALSE;
// set the output folder here // set the output folder here
outputFolder = "generated-code/rust-server"; outputFolder = "generated-code/rust-server";
@@ -529,19 +532,6 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
List<String> consumes = new ArrayList<String>(); List<String> consumes = new ArrayList<String>();
/* comment out the following logic as there's no consume in operation/global definition
if (consumes != null) {
if (!consumes.isEmpty()) {
// use consumes defined in the operation
consumes = operation.getConsumes();
}
} else if (openAPI != null && openAPI.getConsumes() != null && swagger.getConsumes().size() > 0) {
// use consumes defined globally
consumes = swagger.getConsumes();
LOGGER.debug("No consumes defined in operation. Using global consumes (" + swagger.getConsumes() + ") for " + op.operationId);
}
*/
boolean consumesPlainText = false; boolean consumesPlainText = false;
boolean consumesXml = false; boolean consumesXml = false;
// if "consumes" is defined (per operation or using global definition) // if "consumes" is defined (per operation or using global definition)
@@ -569,19 +559,6 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
List<String> produces = new ArrayList<String>(getProducesInfo(openAPI, operation)); List<String> produces = new ArrayList<String>(getProducesInfo(openAPI, operation));
// if "consumes" is defined (per operation or using global definition)
/*
if (operation.getProduces() != null) {
if (operation.getProduces().size() > 0) {
// use produces defined in the operation
produces = operation.getProduces();
}
} else if (swagger != null && swagger.getProduces() != null && swagger.getProduces().size() > 0) {
// use produces defined globally
produces = swagger.getProduces();
LOGGER.debug("No produces defined in operation. Using global produces (" + swagger.getProduces() + ") for " + op.operationId);
}
*/
boolean producesXml = false; boolean producesXml = false;
boolean producesPlainText = false; boolean producesPlainText = false;
@@ -604,51 +581,6 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
op.hasProduces = true; op.hasProduces = true;
} }
/* TODO move the following logic to postProcessOperations as there's no body/form parameter in OAS 3.0
if (op.bodyParam != null) {
if (paramHasXmlNamespace(op.bodyParam, definitions)) {
op.bodyParam.vendorExtensions.put("has_namespace", "true");
}
for (String key : definitions.keySet()) {
op.bodyParam.vendorExtensions.put("model_key", key);
}
// Default to consuming json
op.bodyParam.vendorExtensions.put("uppercase_operation_id", underscore(op.operationId).toUpperCase());
if (consumesXml) {
op.bodyParam.vendorExtensions.put("consumesXml", true);
} else if (consumesPlainText) {
op.bodyParam.vendorExtensions.put("consumesPlainText", true);
} else {
op.bodyParam.vendorExtensions.put("consumesJson", true);
}
}
for (CodegenParameter param : op.bodyParams) {
processParam(param, op);
if (paramHasXmlNamespace(param, definitions)) {
param.vendorExtensions.put("has_namespace", "true");
}
param.vendorExtensions.put("uppercase_operation_id", underscore(op.operationId).toUpperCase());
// Default to producing json if nothing else is specified
if (consumesXml) {
param.vendorExtensions.put("consumesXml", true);
} else if (consumesPlainText) {
param.vendorExtensions.put("consumesPlainText", true);
} else {
param.vendorExtensions.put("consumesJson", true);
}
}
for (CodegenParameter param : op.formParams) {
processParam(param, op);
}
*/
for (CodegenParameter param : op.headerParams) { for (CodegenParameter param : op.headerParams) {
// If a header uses UUIDs, we need to import the UUID package. // If a header uses UUIDs, we need to import the UUID package.
if (param.dataType.equals("uuid::Uuid")) { if (param.dataType.equals("uuid::Uuid")) {
@@ -714,6 +646,77 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
return op; return op;
} }
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation op : operationList) {
boolean consumesPlainText = false;
boolean consumesXml = false;
if (op.consumes != null) {
for (Map<String, String> consume : op.consumes) {
if (consume.get("mediaType") != null) {
String mediaType = consume.get("mediaType");
if (isMimetypeXml(mediaType)) {
additionalProperties.put("usesXml", true);
consumesXml = true;
} else if (isMimetypePlainText(mediaType)) {
consumesPlainText = true;
} else if (isMimetypeWwwFormUrlEncoded(mediaType)) {
additionalProperties.put("usesUrlEncodedForm", true);
}
}
}
}
if (op.bodyParam != null) {
// Default to consuming json
op.bodyParam.vendorExtensions.put("uppercase_operation_id", underscore(op.operationId).toUpperCase());
if (consumesXml) {
op.bodyParam.vendorExtensions.put("consumesXml", true);
} else if (consumesPlainText) {
op.bodyParam.vendorExtensions.put("consumesPlainText", true);
} else {
op.bodyParam.vendorExtensions.put("consumesJson", true);
}
}
for (CodegenParameter param : op.bodyParams) {
processParam(param, op);
param.vendorExtensions.put("uppercase_operation_id", underscore(op.operationId).toUpperCase());
// Default to producing json if nothing else is specified
if (consumesXml) {
param.vendorExtensions.put("consumesXml", true);
} else if (consumesPlainText) {
param.vendorExtensions.put("consumesPlainText", true);
} else {
param.vendorExtensions.put("consumesJson", true);
}
}
for (CodegenParameter param : op.formParams) {
processParam(param, op);
}
for (CodegenProperty header : op.responseHeaders) {
if (header.dataType.equals("uuid::Uuid")) {
additionalProperties.put("apiUsesUuid", true);
}
header.nameInCamelCase = toModelName(header.baseName);
}
additionalProperties.put("apiHasFile", true);
}
return objs;
}
@Override @Override
public boolean isDataTypeFile(final String dataType) { public boolean isDataTypeFile(final String dataType) {
return dataType != null && dataType.equals(typeMapping.get("File").toString()); return dataType != null && dataType.equals(typeMapping.get("File").toString());
@@ -726,26 +729,22 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
Schema inner = ap.getItems(); Schema inner = ap.getItems();
String innerType = getTypeDeclaration(inner); String innerType = getTypeDeclaration(inner);
StringBuilder typeDeclaration = new StringBuilder(typeMapping.get("array")).append("<"); StringBuilder typeDeclaration = new StringBuilder(typeMapping.get("array")).append("<");
if (!StringUtils.isEmpty(inner.get$ref())) {
typeDeclaration.append("models::");
}
typeDeclaration.append(innerType).append(">"); typeDeclaration.append(innerType).append(">");
return typeDeclaration.toString(); return typeDeclaration.toString();
} else if (ModelUtils.isMapSchema(p)) { } else if (ModelUtils.isMapSchema(p)) {
Schema inner = (Schema) p.getAdditionalProperties(); Schema inner = (Schema) p.getAdditionalProperties();
String innerType = getTypeDeclaration(inner); String innerType = getTypeDeclaration(inner);
StringBuilder typeDeclaration = new StringBuilder(typeMapping.get("map")).append("<").append(typeMapping.get("string")).append(", "); StringBuilder typeDeclaration = new StringBuilder(typeMapping.get("map")).append("<").append(typeMapping.get("string")).append(", ");
if (!StringUtils.isEmpty(inner.get$ref())) {
typeDeclaration.append("models::");
}
typeDeclaration.append(innerType).append(">"); typeDeclaration.append(innerType).append(">");
return typeDeclaration.toString(); return typeDeclaration.toString();
} else if (!StringUtils.isEmpty(p.get$ref())) { } else if (!StringUtils.isEmpty(p.get$ref())) {
String datatype; String datatype;
try { try {
datatype = p.get$ref(); datatype = p.get$ref();
if (datatype.indexOf("#/definitions/") == 0) {
datatype = toModelName(datatype.substring("#/definitions/".length())); if (datatype.indexOf("#/components/schemas/") == 0) {
datatype = toModelName(datatype.substring("#/components/schemas/".length()));
datatype = "models::" + datatype;
} }
} catch (Exception e) { } catch (Exception e) {
LOGGER.warn("Error obtaining the datatype from schema (model):" + p + ". Datatype default to Object"); LOGGER.warn("Error obtaining the datatype from schema (model):" + p + ". Datatype default to Object");
@@ -756,50 +755,41 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
} else if (p instanceof FileSchema) { } else if (p instanceof FileSchema) {
return typeMapping.get("File").toString(); return typeMapping.get("File").toString();
} }
return super.getTypeDeclaration(p); return super.getTypeDeclaration(p);
} }
@Override @Override
public CodegenParameter fromParameter(Parameter param, Set<String> imports) { public CodegenParameter fromParameter(Parameter param, Set<String> imports) {
CodegenParameter parameter = super.fromParameter(param, imports); CodegenParameter parameter = super.fromParameter(param, imports);
/* TODO need ot revise the logic below as there's no body parameter if (!parameter.isString && !parameter.isNumeric && !parameter.isByteArray &&
if (param instanceof BodyParameter) { !parameter.isBinary && !parameter.isFile && !parameter.isBoolean &&
BodyParameter bp = (BodyParameter) param; !parameter.isDate && !parameter.isDateTime && !parameter.isUuid &&
Model model = bp.getSchema(); !parameter.isListContainer && !parameter.isMapContainer &&
if (model instanceof RefModel) { !languageSpecificPrimitives.contains(parameter.dataType)) {
String name = ((RefModel) model).getSimpleRef();
name = toModelName(name);
// We need to be able to look up the model in the model definitions later.
parameter.vendorExtensions.put("uppercase_data_type", name.toUpperCase());
name = "models::" + getTypeDeclaration(name); String name = "models::" + getTypeDeclaration(parameter.dataType);
parameter.baseType = name; parameter.dataType = name;
parameter.dataType = name; parameter.baseType = name;
String refName = ((RefModel) model).get$ref();
if (refName.indexOf("#/definitions/") == 0) {
refName = refName.substring("#/definitions/".length());
}
parameter.vendorExtensions.put("refName", refName);
} else if (model instanceof ModelImpl) {
parameter.vendorExtensions.put("refName", ((ModelImpl) model).getName());
}
} }
*/
return parameter; return parameter;
} }
@Override @Override
public CodegenProperty fromProperty(String name, Schema p) { public void postProcessParameter(CodegenParameter parameter) {
CodegenProperty property = super.fromProperty(name, p); // If this parameter is not a primitive type, prefix it with "models::"
// to ensure it's namespaced correctly in the Rust code.
if (!parameter.isString && !parameter.isNumeric && !parameter.isByteArray &&
!parameter.isBinary && !parameter.isFile && !parameter.isBoolean &&
!parameter.isDate && !parameter.isDateTime && !parameter.isUuid &&
!parameter.isListContainer && !parameter.isMapContainer &&
!languageSpecificPrimitives.contains(parameter.dataType)) {
/* need to revise the logic below. Is this for alias? String name = "models::" + getTypeDeclaration(parameter.dataType);
if (p instanceof RefProperty) { parameter.dataType = name;
property.datatype = "models::" + property.datatype; parameter.baseType = name;
} }
*/
return property;
} }
@Override @Override
@@ -1037,6 +1027,24 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
@Override @Override
public Map<String, Object> postProcessModels(Map<String, Object> objs) { public Map<String, Object> postProcessModels(Map<String, Object> objs) {
List<Object> models = (List<Object>) objs.get("models");
for (Object _mo : models) {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
if (cm.dataType != null && cm.dataType.equals("object")) {
// Object isn't a sensible default. Instead, we set it to
// 'null'. This ensures that we treat this model as a struct
// with multiple parameters.
cm.dataType = null;
} else if (cm.dataType != null) {
// We need to hack about with single-parameter models to get
// them recognised correctly.
cm.isAlias = false;
cm.dataType = typeMapping.get(cm.dataType);
}
}
return super.postProcessModelsEnum(objs); return super.postProcessModelsEnum(objs);
} }
@@ -1061,7 +1069,12 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
private void processParam(CodegenParameter param, CodegenOperation op) { private void processParam(CodegenParameter param, CodegenOperation op) {
String example = null; String example = null;
if (param.isString) { if (param.isFile) {
param.vendorExtensions.put("formatString", "{:?}");
op.vendorExtensions.put("hasFile", true);
additionalProperties.put("apiHasFile", true);
example = "Box::new(stream::once(Ok(b\"hello\".to_vec()))) as Box<Stream<Item=_, Error=_> + Send>";
} else if (param.isString) {
if (param.dataFormat != null && param.dataFormat.equals("byte")) { if (param.dataFormat != null && param.dataFormat.equals("byte")) {
param.vendorExtensions.put("formatString", "\\\"{:?}\\\""); param.vendorExtensions.put("formatString", "\\\"{:?}\\\"");
example = "swagger::ByteArray(\"" + ((param.example != null) ? param.example : "") + "\".to_string().into_bytes())"; example = "swagger::ByteArray(\"" + ((param.example != null) ? param.example : "") + "\".to_string().into_bytes())";
@@ -1082,11 +1095,6 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
} else if (param.isListContainer) { } else if (param.isListContainer) {
param.vendorExtensions.put("formatString", "{:?}"); param.vendorExtensions.put("formatString", "{:?}");
example = (param.example != null) ? param.example : "&Vec::new()"; example = (param.example != null) ? param.example : "&Vec::new()";
} else if (param.isFile) {
param.vendorExtensions.put("formatString", "{:?}");
op.vendorExtensions.put("hasFile", true);
additionalProperties.put("apiHasFile", true);
example = "Box::new(stream::once(Ok(b\"hello\".to_vec()))) as Box<Stream<Item=_, Error=_> + Send>";
} else { } else {
param.vendorExtensions.put("formatString", "{:?}"); param.vendorExtensions.put("formatString", "{:?}");
if (param.example != null) { if (param.example != null) {

View File

@@ -137,7 +137,7 @@ public class ModelUtils {
visitOpenAPI(openAPI, (s, t) -> { visitOpenAPI(openAPI, (s, t) -> {
if(s.get$ref() != null) { if(s.get$ref() != null) {
String ref = getSimpleRef(s.get$ref()); String ref = getSimpleRef(s.get$ref());
if ("application/x-www-form-urlencoded".equalsIgnoreCase(t) || if ("application/x-www-form-urlencoded".equalsIgnoreCase(t) ||
"multipart/form-data".equalsIgnoreCase(t)) { "multipart/form-data".equalsIgnoreCase(t)) {
schemasUsedInFormParam.add(ref); schemasUsedInFormParam.add(ref);
} else { } else {
@@ -153,7 +153,7 @@ public class ModelUtils {
* {@link #getUnusedSchemas(OpenAPI)}, * {@link #getUnusedSchemas(OpenAPI)},
* {@link #getSchemasUsedOnlyInFormParam(OpenAPI)}, ...) to traverse all paths of an * {@link #getSchemasUsedOnlyInFormParam(OpenAPI)}, ...) to traverse all paths of an
* OpenAPI instance and call the visitor functional interface when a schema is found. * OpenAPI instance and call the visitor functional interface when a schema is found.
* *
* @param openAPI specification * @param openAPI specification
* @param visitor functional interface (can be defined as a lambda) called each time a schema is found. * @param visitor functional interface (can be defined as a lambda) called each time a schema is found.
*/ */
@@ -492,7 +492,7 @@ public class ModelUtils {
} }
return schema; return schema;
} }
public static Schema getSchema(OpenAPI openAPI, String name) { public static Schema getSchema(OpenAPI openAPI, String name) {
if (name == null) { if (name == null) {
return null; return null;

View File

@@ -15,7 +15,9 @@ To see how to make this your own, look here:
[README]((https://openapi-generator.tech)) [README]((https://openapi-generator.tech))
- API version: {{appVersion}} - API version: {{appVersion}}
{{^hideGenerationTimestamp}}
- Build date: {{generatedDate}} - Build date: {{generatedDate}}
{{/hideGenerationTimestamp}}
{{#infoUrl}} {{#infoUrl}}
For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})
{{/infoUrl}} {{/infoUrl}}

View File

@@ -1 +1 @@
{{{swagger-yaml}}} {{{openapi-yaml}}}

View File

@@ -1,11 +1,11 @@
# Swagger Codegen Ignore # OpenAPI Generator Ignore
# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen # Generated by openapi-generator https://github.com/openapitools/openapi-generator
# Use this file to prevent files from being overwritten by the generator. # Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore. # The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs. # 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: # You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs #ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*): # You can match any string of characters against a directory, file or extension with a single asterisk (*):

View File

@@ -1 +1 @@
2.4.0-SNAPSHOT 3.0.1-SNAPSHOT

View File

@@ -1,7 +1,7 @@
[package] [package]
name = "petstore_api" name = "petstore_api"
version = "1.0.0" version = "1.0.0"
authors = ["apiteam@swagger.io"] authors = []
description = "This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\" description = "This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\"
license = "Unlicense" license = "Unlicense"
@@ -17,7 +17,7 @@ chrono = { version = "0.4", features = ["serde"] }
futures = "0.1" futures = "0.1"
hyper = {version = "0.11", optional = true} hyper = {version = "0.11", optional = true}
hyper-tls = {version = "0.1.2", optional = true} hyper-tls = {version = "0.1.2", optional = true}
swagger = "0.10.0" swagger = "0.12.1"
# Not required by example server. # Not required by example server.
# #

View File

@@ -3,17 +3,16 @@
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
## Overview ## Overview
This client/server was generated by the [swagger-codegen] This client/server was generated by the [openapi-generator]
(https://github.com/swagger-api/swagger-codegen) project. (https://openapi-generator.tech) project.
By using the [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate a server stub. By using the [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate a server stub.
- -
To see how to make this your own, look here: To see how to make this your own, look here:
[README](https://github.com/swagger-api/swagger-codegen/blob/master/README.md) [README]((https://openapi-generator.tech))
- API version: 1.0.0 - API version: 1.0.0
- Build date: 2018-04-03T12:24:00.479+01:00
This autogenerated project defines an API crate `petstore_api` which contains: This autogenerated project defines an API crate `petstore_api` which contains:
* An `Api` trait defining the API in Rust. * An `Api` trait defining the API in Rust.
@@ -57,11 +56,11 @@ To run a client, follow one of the following simple steps:
``` ```
cargo run --example client TestSpecialTags cargo run --example client TestSpecialTags
cargo run --example client TestBodyWithQueryParams
cargo run --example client FakeOuterBooleanSerialize cargo run --example client FakeOuterBooleanSerialize
cargo run --example client FakeOuterCompositeSerialize cargo run --example client FakeOuterCompositeSerialize
cargo run --example client FakeOuterNumberSerialize cargo run --example client FakeOuterNumberSerialize
cargo run --example client FakeOuterStringSerialize cargo run --example client FakeOuterStringSerialize
cargo run --example client TestBodyWithQueryParams
cargo run --example client TestClientModel cargo run --example client TestClientModel
cargo run --example client TestEndpointParameters cargo run --example client TestEndpointParameters
cargo run --example client TestEnumParameters cargo run --example client TestEnumParameters

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -4,12 +4,15 @@ extern crate petstore_api;
#[allow(unused_extern_crates)] #[allow(unused_extern_crates)]
extern crate futures; extern crate futures;
#[allow(unused_extern_crates)] #[allow(unused_extern_crates)]
#[macro_use]
extern crate swagger; extern crate swagger;
#[allow(unused_extern_crates)] #[allow(unused_extern_crates)]
extern crate uuid; extern crate uuid;
extern crate clap; extern crate clap;
extern crate tokio_core; extern crate tokio_core;
use swagger::{ContextBuilder, EmptyContext, XSpanIdString, Has, Push, AuthData};
#[allow(unused_imports)] #[allow(unused_imports)]
use futures::{Future, future, Stream, stream}; use futures::{Future, future, Stream, stream};
use tokio_core::reactor; use tokio_core::reactor;
@@ -17,11 +20,11 @@ use tokio_core::reactor;
use petstore_api::{ApiNoContext, ContextWrapperExt, use petstore_api::{ApiNoContext, ContextWrapperExt,
ApiError, ApiError,
TestSpecialTagsResponse, TestSpecialTagsResponse,
TestBodyWithQueryParamsResponse,
FakeOuterBooleanSerializeResponse, FakeOuterBooleanSerializeResponse,
FakeOuterCompositeSerializeResponse, FakeOuterCompositeSerializeResponse,
FakeOuterNumberSerializeResponse, FakeOuterNumberSerializeResponse,
FakeOuterStringSerializeResponse, FakeOuterStringSerializeResponse,
TestBodyWithQueryParamsResponse,
TestClientModelResponse, TestClientModelResponse,
TestEndpointParametersResponse, TestEndpointParametersResponse,
TestEnumParametersResponse, TestEnumParametersResponse,
@@ -112,179 +115,180 @@ fn main() {
.expect("Failed to create HTTP client") .expect("Failed to create HTTP client")
}; };
// Using a non-default `Context` is not required; this is just an example! let context: make_context_ty!(ContextBuilder, EmptyContext, Option<AuthData>, XSpanIdString) =
let client = client.with_context(petstore_api::Context::new_with_span_id(self::uuid::Uuid::new_v4().to_string())); make_context!(ContextBuilder, EmptyContext, None, XSpanIdString(self::uuid::Uuid::new_v4().to_string()));
let client = client.with_context(context);
match matches.value_of("operation") { match matches.value_of("operation") {
// Disabled because there's no example. // Disabled because there's no example.
// Some("TestSpecialTags") => { // Some("TestSpecialTags") => {
// let result = core.run(client.test_special_tags(???)); // let result = core.run(client.test_special_tags(???));
// println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
// },
// Disabled because there's no example.
// Some("TestBodyWithQueryParams") => {
// let result = core.run(client.test_body_with_query_params(???, "query_example".to_string()));
// println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>")));
// }, // },
Some("FakeOuterBooleanSerialize") => { Some("FakeOuterBooleanSerialize") => {
let result = core.run(client.fake_outer_boolean_serialize(None)); let result = core.run(client.fake_outer_boolean_serialize(Some(true)));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
}, },
Some("FakeOuterCompositeSerialize") => { Some("FakeOuterCompositeSerialize") => {
let result = core.run(client.fake_outer_composite_serialize(None)); let result = core.run(client.fake_outer_composite_serialize(None));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
}, },
Some("FakeOuterNumberSerialize") => { Some("FakeOuterNumberSerialize") => {
let result = core.run(client.fake_outer_number_serialize(None)); let result = core.run(client.fake_outer_number_serialize(Some(1.2)));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
}, },
Some("FakeOuterStringSerialize") => { Some("FakeOuterStringSerialize") => {
let result = core.run(client.fake_outer_string_serialize(None)); let result = core.run(client.fake_outer_string_serialize(Some("body_example".to_string())));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
}, },
// Disabled because there's no example.
// Some("TestBodyWithQueryParams") => {
// let result = core.run(client.test_body_with_query_params("query_example".to_string(), ???));
// println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
// },
// Disabled because there's no example. // Disabled because there's no example.
// Some("TestClientModel") => { // Some("TestClientModel") => {
// let result = core.run(client.test_client_model(???)); // let result = core.run(client.test_client_model(???));
// println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
// }, // },
Some("TestEndpointParameters") => { Some("TestEndpointParameters") => {
let result = core.run(client.test_endpoint_parameters(8.14, 1.2, "pattern_without_delimiter_example".to_string(), swagger::ByteArray(Vec::from("B")), Some(56), Some(56), Some(789), Some(3.4), Some("string_example".to_string()), Some(swagger::ByteArray(Vec::from("B"))), None, None, Some("password_example".to_string()), Some("callback_example".to_string()))); let result = core.run(client.test_endpoint_parameters(8.14, 1.2, "pattern_without_delimiter_example".to_string(), Some(56), Some(56), Some(789), Some(3.4), Some("string_example".to_string()), Box::new(future::ok(Some(Box::new(stream::once(Ok(b"hello".to_vec()))) as Box<Stream<Item=_, Error=_> + Send>))) as Box<Future<Item=_, Error=_> + Send>, None, None, Some("password_example".to_string()), Some("callback_example".to_string())));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
}, },
Some("TestEnumParameters") => { Some("TestEnumParameters") => {
let result = core.run(client.test_enum_parameters(Some(&Vec::new()), Some("enum_form_string_example".to_string()), Some(&Vec::new()), Some("enum_header_string_example".to_string()), Some(&Vec::new()), Some("enum_query_string_example".to_string()), Some(56), Some(1.2))); let result = core.run(client.test_enum_parameters(Some(&Vec::new()), Some("enum_header_string_example".to_string()), Some(&Vec::new()), Some("enum_query_string_example".to_string()), Some(56), Some(1.2)));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
}, },
// Disabled because there's no example. // Disabled because there's no example.
// Some("TestInlineAdditionalProperties") => { // Some("TestInlineAdditionalProperties") => {
// let result = core.run(client.test_inline_additional_properties(???)); // let result = core.run(client.test_inline_additional_properties(???));
// println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
// }, // },
Some("TestJsonFormData") => { Some("TestJsonFormData") => {
let result = core.run(client.test_json_form_data("param_example".to_string(), "param2_example".to_string())); let result = core.run(client.test_json_form_data("param_example".to_string(), "param2_example".to_string()));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
}, },
// Disabled because there's no example. // Disabled because there's no example.
// Some("TestClassname") => { // Some("TestClassname") => {
// let result = core.run(client.test_classname(???)); // let result = core.run(client.test_classname(???));
// println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
// }, // },
// Disabled because there's no example. // Disabled because there's no example.
// Some("AddPet") => { // Some("AddPet") => {
// let result = core.run(client.add_pet(???)); // let result = core.run(client.add_pet(???));
// println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
// }, // },
Some("DeletePet") => { Some("DeletePet") => {
let result = core.run(client.delete_pet(789, Some("api_key_example".to_string()))); let result = core.run(client.delete_pet(789, Some("api_key_example".to_string())));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
}, },
Some("FindPetsByStatus") => { Some("FindPetsByStatus") => {
let result = core.run(client.find_pets_by_status(&Vec::new())); let result = core.run(client.find_pets_by_status(&Vec::new()));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
}, },
Some("FindPetsByTags") => { Some("FindPetsByTags") => {
let result = core.run(client.find_pets_by_tags(&Vec::new())); let result = core.run(client.find_pets_by_tags(&Vec::new()));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
}, },
Some("GetPetById") => { Some("GetPetById") => {
let result = core.run(client.get_pet_by_id(789)); let result = core.run(client.get_pet_by_id(789));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
}, },
// Disabled because there's no example. // Disabled because there's no example.
// Some("UpdatePet") => { // Some("UpdatePet") => {
// let result = core.run(client.update_pet(???)); // let result = core.run(client.update_pet(???));
// println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
// }, // },
Some("UpdatePetWithForm") => { Some("UpdatePetWithForm") => {
let result = core.run(client.update_pet_with_form(789, Some("name_example".to_string()), Some("status_example".to_string()))); let result = core.run(client.update_pet_with_form(789, Some("name_example".to_string()), Some("status_example".to_string())));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
}, },
Some("UploadFile") => { Some("UploadFile") => {
let result = core.run(client.upload_file(789, Some("additional_metadata_example".to_string()), Box::new(future::ok(Some(Box::new(stream::once(Ok(b"hello".to_vec()))) as Box<Stream<Item=_, Error=_> + Send>))) as Box<Future<Item=_, Error=_> + Send>)); let result = core.run(client.upload_file(789, Some("additional_metadata_example".to_string()), Box::new(future::ok(Some(Box::new(stream::once(Ok(b"hello".to_vec()))) as Box<Stream<Item=_, Error=_> + Send>))) as Box<Future<Item=_, Error=_> + Send>));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
}, },
Some("DeleteOrder") => { Some("DeleteOrder") => {
let result = core.run(client.delete_order("order_id_example".to_string())); let result = core.run(client.delete_order("order_id_example".to_string()));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
}, },
Some("GetInventory") => { Some("GetInventory") => {
let result = core.run(client.get_inventory()); let result = core.run(client.get_inventory());
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
}, },
Some("GetOrderById") => { Some("GetOrderById") => {
let result = core.run(client.get_order_by_id(789)); let result = core.run(client.get_order_by_id(789));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
}, },
// Disabled because there's no example. // Disabled because there's no example.
// Some("PlaceOrder") => { // Some("PlaceOrder") => {
// let result = core.run(client.place_order(???)); // let result = core.run(client.place_order(???));
// println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
// }, // },
// Disabled because there's no example. // Disabled because there's no example.
// Some("CreateUser") => { // Some("CreateUser") => {
// let result = core.run(client.create_user(???)); // let result = core.run(client.create_user(???));
// println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
// }, // },
Some("CreateUsersWithArrayInput") => { Some("CreateUsersWithArrayInput") => {
let result = core.run(client.create_users_with_array_input(&Vec::new())); let result = core.run(client.create_users_with_array_input(&Vec::new()));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
}, },
Some("CreateUsersWithListInput") => { Some("CreateUsersWithListInput") => {
let result = core.run(client.create_users_with_list_input(&Vec::new())); let result = core.run(client.create_users_with_list_input(&Vec::new()));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
}, },
Some("DeleteUser") => { Some("DeleteUser") => {
let result = core.run(client.delete_user("username_example".to_string())); let result = core.run(client.delete_user("username_example".to_string()));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
}, },
Some("GetUserByName") => { Some("GetUserByName") => {
let result = core.run(client.get_user_by_name("username_example".to_string())); let result = core.run(client.get_user_by_name("username_example".to_string()));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
}, },
Some("LoginUser") => { Some("LoginUser") => {
let result = core.run(client.login_user("username_example".to_string(), "password_example".to_string())); let result = core.run(client.login_user("username_example".to_string(), "password_example".to_string()));
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
}, },
Some("LogoutUser") => { Some("LogoutUser") => {
let result = core.run(client.logout_user()); let result = core.run(client.logout_user());
println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
}, },
// Disabled because there's no example. // Disabled because there's no example.
// Some("UpdateUser") => { // Some("UpdateUser") => {
// let result = core.run(client.update_user("username_example".to_string(), ???)); // let result = core.run(client.update_user("username_example".to_string(), ???));
// println!("{:?} (X-Span-ID: {:?})", result, client.context().x_span_id.clone().unwrap_or(String::from("<none>"))); // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has<XSpanIdString>).get().clone());
// }, // },
_ => { _ => {

View File

@@ -29,6 +29,7 @@ use hyper::server::Http;
use tokio_proto::TcpServer; use tokio_proto::TcpServer;
use clap::{App, Arg}; use clap::{App, Arg};
use swagger::auth::AllowAllAuthenticator; use swagger::auth::AllowAllAuthenticator;
use swagger::EmptyContext;
mod server_lib; mod server_lib;
@@ -54,9 +55,9 @@ fn main() {
.get_matches(); .get_matches();
let service_fn = let service_fn =
petstore_api::server::auth::NewService::new( petstore_api::server::auth::NewService::<_, EmptyContext>::new(
AllowAllAuthenticator::new( AllowAllAuthenticator::new(
server_lib::NewService, server_lib::NewService::new(),
"cosmo" "cosmo"
) )
); );

View File

@@ -8,19 +8,31 @@ mod errors {
pub use self::errors::*; pub use self::errors::*;
use std::io; use std::io;
use std::clone::Clone;
use std::marker::PhantomData;
use hyper; use hyper;
use petstore_api; use petstore_api;
use swagger::{Has, XSpanIdString};
use swagger::auth::Authorization;
pub struct NewService; pub struct NewService<C>{
marker: PhantomData<C>
}
impl hyper::server::NewService for NewService { impl<C> NewService<C>{
type Request = (hyper::Request, petstore_api::Context); pub fn new() -> Self {
NewService{marker:PhantomData}
}
}
impl<C> hyper::server::NewService for NewService<C> where C: Has<XSpanIdString> + Has<Option<Authorization>> + Clone + 'static {
type Request = (hyper::Request, C);
type Response = hyper::Response; type Response = hyper::Response;
type Error = hyper::Error; type Error = hyper::Error;
type Instance = petstore_api::server::Service<server::Server>; type Instance = petstore_api::server::Service<server::Server<C>, C>;
/// Instantiate a new server. /// Instantiate a new server.
fn new_service(&self) -> io::Result<Self::Instance> { fn new_service(&self) -> io::Result<Self::Instance> {
Ok(petstore_api::server::Service::new(server::Server)) Ok(petstore_api::server::Service::new(server::Server::new()))
} }
} }

View File

@@ -7,16 +7,18 @@ use chrono;
use futures::Stream; use futures::Stream;
use std::collections::HashMap; use std::collections::HashMap;
use std::io::Error; use std::io::Error;
use std::marker::PhantomData;
use swagger; use swagger;
use swagger::{Has, XSpanIdString};
use petstore_api::{Api, ApiError, Context, use petstore_api::{Api, ApiError,
TestSpecialTagsResponse, TestSpecialTagsResponse,
TestBodyWithQueryParamsResponse,
FakeOuterBooleanSerializeResponse, FakeOuterBooleanSerializeResponse,
FakeOuterCompositeSerializeResponse, FakeOuterCompositeSerializeResponse,
FakeOuterNumberSerializeResponse, FakeOuterNumberSerializeResponse,
FakeOuterStringSerializeResponse, FakeOuterStringSerializeResponse,
TestBodyWithQueryParamsResponse,
TestClientModelResponse, TestClientModelResponse,
TestEndpointParametersResponse, TestEndpointParametersResponse,
TestEnumParametersResponse, TestEnumParametersResponse,
@@ -47,232 +49,241 @@ use petstore_api::{Api, ApiError, Context,
use petstore_api::models; use petstore_api::models;
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
pub struct Server; pub struct Server<C> {
marker: PhantomData<C>,
}
impl Api for Server { impl<C> Server<C> {
pub fn new() -> Self {
Server{marker: PhantomData}
}
}
impl<C> Api<C> for Server<C> where C: Has<XSpanIdString>{
/// To test special tags /// To test special tags
fn test_special_tags(&self, body: models::Client, context: &Context) -> Box<Future<Item=TestSpecialTagsResponse, Error=ApiError>> { fn test_special_tags(&self, client: models::Client, context: &C) -> Box<Future<Item=TestSpecialTagsResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("test_special_tags({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("test_special_tags({:?}) - X-Span-ID: {:?}", client, context.get().0.clone());
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
fn test_body_with_query_params(&self, body: models::User, query: String, context: &Context) -> Box<Future<Item=TestBodyWithQueryParamsResponse, Error=ApiError>> { fn fake_outer_boolean_serialize(&self, body: Option<bool>, context: &C) -> Box<Future<Item=FakeOuterBooleanSerializeResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("test_body_with_query_params({:?}, \"{}\") - X-Span-ID: {:?}", body, query, context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("fake_outer_boolean_serialize({:?}) - X-Span-ID: {:?}", body, context.get().0.clone());
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
fn fake_outer_boolean_serialize(&self, body: Option<models::OuterBoolean>, context: &Context) -> Box<Future<Item=FakeOuterBooleanSerializeResponse, Error=ApiError>> { fn fake_outer_composite_serialize(&self, outer_composite: Option<models::OuterComposite>, context: &C) -> Box<Future<Item=FakeOuterCompositeSerializeResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("fake_outer_boolean_serialize({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("fake_outer_composite_serialize({:?}) - X-Span-ID: {:?}", outer_composite, context.get().0.clone());
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
fn fake_outer_composite_serialize(&self, body: Option<models::OuterComposite>, context: &Context) -> Box<Future<Item=FakeOuterCompositeSerializeResponse, Error=ApiError>> { fn fake_outer_number_serialize(&self, body: Option<f64>, context: &C) -> Box<Future<Item=FakeOuterNumberSerializeResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("fake_outer_composite_serialize({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("fake_outer_number_serialize({:?}) - X-Span-ID: {:?}", body, context.get().0.clone());
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
fn fake_outer_number_serialize(&self, body: Option<models::OuterNumber>, context: &Context) -> Box<Future<Item=FakeOuterNumberSerializeResponse, Error=ApiError>> { fn fake_outer_string_serialize(&self, body: Option<String>, context: &C) -> Box<Future<Item=FakeOuterStringSerializeResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("fake_outer_number_serialize({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("fake_outer_string_serialize({:?}) - X-Span-ID: {:?}", body, context.get().0.clone());
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
fn fake_outer_string_serialize(&self, body: Option<models::OuterString>, context: &Context) -> Box<Future<Item=FakeOuterStringSerializeResponse, Error=ApiError>> { fn test_body_with_query_params(&self, query: String, user: models::User, context: &C) -> Box<Future<Item=TestBodyWithQueryParamsResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("fake_outer_string_serialize({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("test_body_with_query_params(\"{}\", {:?}) - X-Span-ID: {:?}", query, user, context.get().0.clone());
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
/// To test \"client\" model /// To test \"client\" model
fn test_client_model(&self, body: models::Client, context: &Context) -> Box<Future<Item=TestClientModelResponse, Error=ApiError>> { fn test_client_model(&self, client: models::Client, context: &C) -> Box<Future<Item=TestClientModelResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("test_client_model({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("test_client_model({:?}) - X-Span-ID: {:?}", client, context.get().0.clone());
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
/// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option<i32>, int32: Option<i32>, int64: Option<i64>, float: Option<f32>, string: Option<String>, binary: Option<swagger::ByteArray>, date: Option<chrono::DateTime<chrono::Utc>>, date_time: Option<chrono::DateTime<chrono::Utc>>, password: Option<String>, callback: Option<String>, context: &Context) -> Box<Future<Item=TestEndpointParametersResponse, Error=ApiError>> { fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, integer: Option<i32>, int32: Option<i32>, int64: Option<i64>, float: Option<f32>, string: Option<String>, binary: Box<Future<Item=Option<Box<Stream<Item=Vec<u8>, Error=Error> + Send>>, Error=Error> + Send>, date: Option<chrono::DateTime<chrono::Utc>>, date_time: Option<chrono::DateTime<chrono::Utc>>, password: Option<String>, callback: Option<String>, context: &C) -> Box<Future<Item=TestEndpointParametersResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("test_endpoint_parameters({}, {}, \"{}\", {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}) - X-Span-ID: {:?}", number, double, pattern_without_delimiter, byte, integer, int32, int64, float, string, binary, date, date_time, password, callback, context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("test_endpoint_parameters({}, {}, \"{}\", {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}) - X-Span-ID: {:?}", number, double, pattern_without_delimiter, integer, int32, int64, float, string, date, date_time, password, callback, context.get().0.clone());
let _ = binary; //Suppresses unused param warning
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
/// To test enum parameters /// To test enum parameters
fn test_enum_parameters(&self, enum_form_string_array: Option<&Vec<String>>, enum_form_string: Option<String>, enum_header_string_array: Option<&Vec<String>>, enum_header_string: Option<String>, enum_query_string_array: Option<&Vec<String>>, enum_query_string: Option<String>, enum_query_integer: Option<i32>, enum_query_double: Option<f64>, context: &Context) -> Box<Future<Item=TestEnumParametersResponse, Error=ApiError>> { fn test_enum_parameters(&self, enum_header_string_array: Option<&Vec<String>>, enum_header_string: Option<String>, enum_query_string_array: Option<&Vec<String>>, enum_query_string: Option<String>, enum_query_integer: Option<i32>, enum_query_double: Option<f64>, context: &C) -> Box<Future<Item=TestEnumParametersResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("test_enum_parameters({:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}) - X-Span-ID: {:?}", enum_form_string_array, enum_form_string, enum_header_string_array, enum_header_string, enum_query_string_array, enum_query_string, enum_query_integer, enum_query_double, context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("test_enum_parameters({:?}, {:?}, {:?}, {:?}, {:?}, {:?}) - X-Span-ID: {:?}", enum_header_string_array, enum_header_string, enum_query_string_array, enum_query_string, enum_query_integer, enum_query_double, context.get().0.clone());
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
/// test inline additionalProperties /// test inline additionalProperties
fn test_inline_additional_properties(&self, param: object, context: &Context) -> Box<Future<Item=TestInlineAdditionalPropertiesResponse, Error=ApiError>> { fn test_inline_additional_properties(&self, request_body: HashMap<String, String>, context: &C) -> Box<Future<Item=TestInlineAdditionalPropertiesResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("test_inline_additional_properties({:?}) - X-Span-ID: {:?}", param, context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("test_inline_additional_properties({:?}) - X-Span-ID: {:?}", request_body, context.get().0.clone());
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
/// test json serialization of form data /// test json serialization of form data
fn test_json_form_data(&self, param: String, param2: String, context: &Context) -> Box<Future<Item=TestJsonFormDataResponse, Error=ApiError>> { fn test_json_form_data(&self, param: String, param2: String, context: &C) -> Box<Future<Item=TestJsonFormDataResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("test_json_form_data(\"{}\", \"{}\") - X-Span-ID: {:?}", param, param2, context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("test_json_form_data(\"{}\", \"{}\") - X-Span-ID: {:?}", param, param2, context.get().0.clone());
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
/// To test class name in snake case /// To test class name in snake case
fn test_classname(&self, body: models::Client, context: &Context) -> Box<Future<Item=TestClassnameResponse, Error=ApiError>> { fn test_classname(&self, client: models::Client, context: &C) -> Box<Future<Item=TestClassnameResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("test_classname({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("test_classname({:?}) - X-Span-ID: {:?}", client, context.get().0.clone());
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
/// Add a new pet to the store /// Add a new pet to the store
fn add_pet(&self, body: models::Pet, context: &Context) -> Box<Future<Item=AddPetResponse, Error=ApiError>> { fn add_pet(&self, pet: models::Pet, context: &C) -> Box<Future<Item=AddPetResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("add_pet({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("add_pet({:?}) - X-Span-ID: {:?}", pet, context.get().0.clone());
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
/// Deletes a pet /// Deletes a pet
fn delete_pet(&self, pet_id: i64, api_key: Option<String>, context: &Context) -> Box<Future<Item=DeletePetResponse, Error=ApiError>> { fn delete_pet(&self, pet_id: i64, api_key: Option<String>, context: &C) -> Box<Future<Item=DeletePetResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("delete_pet({}, {:?}) - X-Span-ID: {:?}", pet_id, api_key, context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("delete_pet({}, {:?}) - X-Span-ID: {:?}", pet_id, api_key, context.get().0.clone());
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
/// Finds Pets by status /// Finds Pets by status
fn find_pets_by_status(&self, status: &Vec<String>, context: &Context) -> Box<Future<Item=FindPetsByStatusResponse, Error=ApiError>> { fn find_pets_by_status(&self, status: &Vec<String>, context: &C) -> Box<Future<Item=FindPetsByStatusResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("find_pets_by_status({:?}) - X-Span-ID: {:?}", status, context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("find_pets_by_status({:?}) - X-Span-ID: {:?}", status, context.get().0.clone());
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
/// Finds Pets by tags /// Finds Pets by tags
fn find_pets_by_tags(&self, tags: &Vec<String>, context: &Context) -> Box<Future<Item=FindPetsByTagsResponse, Error=ApiError>> { fn find_pets_by_tags(&self, tags: &Vec<String>, context: &C) -> Box<Future<Item=FindPetsByTagsResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("find_pets_by_tags({:?}) - X-Span-ID: {:?}", tags, context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("find_pets_by_tags({:?}) - X-Span-ID: {:?}", tags, context.get().0.clone());
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
/// Find pet by ID /// Find pet by ID
fn get_pet_by_id(&self, pet_id: i64, context: &Context) -> Box<Future<Item=GetPetByIdResponse, Error=ApiError>> { fn get_pet_by_id(&self, pet_id: i64, context: &C) -> Box<Future<Item=GetPetByIdResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("get_pet_by_id({}) - X-Span-ID: {:?}", pet_id, context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("get_pet_by_id({}) - X-Span-ID: {:?}", pet_id, context.get().0.clone());
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
/// Update an existing pet /// Update an existing pet
fn update_pet(&self, body: models::Pet, context: &Context) -> Box<Future<Item=UpdatePetResponse, Error=ApiError>> { fn update_pet(&self, pet: models::Pet, context: &C) -> Box<Future<Item=UpdatePetResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("update_pet({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("update_pet({:?}) - X-Span-ID: {:?}", pet, context.get().0.clone());
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
/// Updates a pet in the store with form data /// Updates a pet in the store with form data
fn update_pet_with_form(&self, pet_id: i64, name: Option<String>, status: Option<String>, context: &Context) -> Box<Future<Item=UpdatePetWithFormResponse, Error=ApiError>> { fn update_pet_with_form(&self, pet_id: i64, name: Option<String>, status: Option<String>, context: &C) -> Box<Future<Item=UpdatePetWithFormResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("update_pet_with_form({}, {:?}, {:?}) - X-Span-ID: {:?}", pet_id, name, status, context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("update_pet_with_form({}, {:?}, {:?}) - X-Span-ID: {:?}", pet_id, name, status, context.get().0.clone());
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
/// uploads an image /// uploads an image
fn upload_file(&self, pet_id: i64, additional_metadata: Option<String>, file: Box<Future<Item=Option<Box<Stream<Item=Vec<u8>, Error=Error> + Send>>, Error=Error> + Send>, context: &Context) -> Box<Future<Item=UploadFileResponse, Error=ApiError>> { fn upload_file(&self, pet_id: i64, additional_metadata: Option<String>, file: Box<Future<Item=Option<Box<Stream<Item=Vec<u8>, Error=Error> + Send>>, Error=Error> + Send>, context: &C) -> Box<Future<Item=UploadFileResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("upload_file({}, {:?}, ) - X-Span-ID: {:?}", pet_id, additional_metadata, context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("upload_file({}, {:?}, ) - X-Span-ID: {:?}", pet_id, additional_metadata, context.get().0.clone());
let _ = file; //Suppresses unused param warning let _ = file; //Suppresses unused param warning
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
/// Delete purchase order by ID /// Delete purchase order by ID
fn delete_order(&self, order_id: String, context: &Context) -> Box<Future<Item=DeleteOrderResponse, Error=ApiError>> { fn delete_order(&self, order_id: String, context: &C) -> Box<Future<Item=DeleteOrderResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("delete_order(\"{}\") - X-Span-ID: {:?}", order_id, context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("delete_order(\"{}\") - X-Span-ID: {:?}", order_id, context.get().0.clone());
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
/// Returns pet inventories by status /// Returns pet inventories by status
fn get_inventory(&self, context: &Context) -> Box<Future<Item=GetInventoryResponse, Error=ApiError>> { fn get_inventory(&self, context: &C) -> Box<Future<Item=GetInventoryResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("get_inventory() - X-Span-ID: {:?}", context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("get_inventory() - X-Span-ID: {:?}", context.get().0.clone());
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
/// Find purchase order by ID /// Find purchase order by ID
fn get_order_by_id(&self, order_id: i64, context: &Context) -> Box<Future<Item=GetOrderByIdResponse, Error=ApiError>> { fn get_order_by_id(&self, order_id: i64, context: &C) -> Box<Future<Item=GetOrderByIdResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("get_order_by_id({}) - X-Span-ID: {:?}", order_id, context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("get_order_by_id({}) - X-Span-ID: {:?}", order_id, context.get().0.clone());
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
/// Place an order for a pet /// Place an order for a pet
fn place_order(&self, body: models::Order, context: &Context) -> Box<Future<Item=PlaceOrderResponse, Error=ApiError>> { fn place_order(&self, order: models::Order, context: &C) -> Box<Future<Item=PlaceOrderResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("place_order({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("place_order({:?}) - X-Span-ID: {:?}", order, context.get().0.clone());
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
/// Create user /// Create user
fn create_user(&self, body: models::User, context: &Context) -> Box<Future<Item=CreateUserResponse, Error=ApiError>> { fn create_user(&self, user: models::User, context: &C) -> Box<Future<Item=CreateUserResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("create_user({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("create_user({:?}) - X-Span-ID: {:?}", user, context.get().0.clone());
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
/// Creates list of users with given input array /// Creates list of users with given input array
fn create_users_with_array_input(&self, body: &Vec<models::User>, context: &Context) -> Box<Future<Item=CreateUsersWithArrayInputResponse, Error=ApiError>> { fn create_users_with_array_input(&self, user: &Vec<models::User>, context: &C) -> Box<Future<Item=CreateUsersWithArrayInputResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("create_users_with_array_input({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("create_users_with_array_input({:?}) - X-Span-ID: {:?}", user, context.get().0.clone());
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
/// Creates list of users with given input array /// Creates list of users with given input array
fn create_users_with_list_input(&self, body: &Vec<models::User>, context: &Context) -> Box<Future<Item=CreateUsersWithListInputResponse, Error=ApiError>> { fn create_users_with_list_input(&self, user: &Vec<models::User>, context: &C) -> Box<Future<Item=CreateUsersWithListInputResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("create_users_with_list_input({:?}) - X-Span-ID: {:?}", body, context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("create_users_with_list_input({:?}) - X-Span-ID: {:?}", user, context.get().0.clone());
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
/// Delete user /// Delete user
fn delete_user(&self, username: String, context: &Context) -> Box<Future<Item=DeleteUserResponse, Error=ApiError>> { fn delete_user(&self, username: String, context: &C) -> Box<Future<Item=DeleteUserResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("delete_user(\"{}\") - X-Span-ID: {:?}", username, context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("delete_user(\"{}\") - X-Span-ID: {:?}", username, context.get().0.clone());
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
/// Get user by user name /// Get user by user name
fn get_user_by_name(&self, username: String, context: &Context) -> Box<Future<Item=GetUserByNameResponse, Error=ApiError>> { fn get_user_by_name(&self, username: String, context: &C) -> Box<Future<Item=GetUserByNameResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("get_user_by_name(\"{}\") - X-Span-ID: {:?}", username, context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("get_user_by_name(\"{}\") - X-Span-ID: {:?}", username, context.get().0.clone());
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
/// Logs user into the system /// Logs user into the system
fn login_user(&self, username: String, password: String, context: &Context) -> Box<Future<Item=LoginUserResponse, Error=ApiError>> { fn login_user(&self, username: String, password: String, context: &C) -> Box<Future<Item=LoginUserResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("login_user(\"{}\", \"{}\") - X-Span-ID: {:?}", username, password, context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("login_user(\"{}\", \"{}\") - X-Span-ID: {:?}", username, password, context.get().0.clone());
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
/// Logs out current logged in user session /// Logs out current logged in user session
fn logout_user(&self, context: &Context) -> Box<Future<Item=LogoutUserResponse, Error=ApiError>> { fn logout_user(&self, context: &C) -> Box<Future<Item=LogoutUserResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("logout_user() - X-Span-ID: {:?}", context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("logout_user() - X-Span-ID: {:?}", context.get().0.clone());
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }
/// Updated user /// Updated user
fn update_user(&self, username: String, body: models::User, context: &Context) -> Box<Future<Item=UpdateUserResponse, Error=ApiError>> { fn update_user(&self, username: String, user: models::User, context: &C) -> Box<Future<Item=UpdateUserResponse, Error=ApiError>> {
let context = context.clone(); let context = context.clone();
println!("update_user(\"{}\", {:?}) - X-Span-ID: {:?}", username, body, context.x_span_id.unwrap_or(String::from("<none>")).clone()); println!("update_user(\"{}\", {:?}) - X-Span-ID: {:?}", username, user, context.get().0.clone());
Box::new(futures::failed("Generic failure".into())) Box::new(futures::failed("Generic failure".into()))
} }

File diff suppressed because it is too large Load Diff

View File

@@ -30,7 +30,7 @@ pub use futures::Future;
#[cfg(any(feature = "client", feature = "server"))] #[cfg(any(feature = "client", feature = "server"))]
mod mimetypes; mod mimetypes;
pub use swagger::{ApiError, Context, ContextWrapper}; pub use swagger::{ApiError, ContextWrapper};
pub const BASE_PATH: &'static str = "/v2"; pub const BASE_PATH: &'static str = "/v2";
pub const API_VERSION: &'static str = "1.0.0"; pub const API_VERSION: &'static str = "1.0.0";
@@ -42,12 +42,6 @@ pub enum TestSpecialTagsResponse {
SuccessfulOperation ( models::Client ) , SuccessfulOperation ( models::Client ) ,
} }
#[derive(Debug, PartialEq)]
pub enum TestBodyWithQueryParamsResponse {
/// Success
Success ,
}
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
pub enum FakeOuterBooleanSerializeResponse { pub enum FakeOuterBooleanSerializeResponse {
/// Output boolean /// Output boolean
@@ -72,6 +66,12 @@ pub enum FakeOuterStringSerializeResponse {
OutputString ( models::OuterString ) , OutputString ( models::OuterString ) ,
} }
#[derive(Debug, PartialEq)]
pub enum TestBodyWithQueryParamsResponse {
/// Success
Success ,
}
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
pub enum TestClientModelResponse { pub enum TestClientModelResponse {
/// successful operation /// successful operation
@@ -242,8 +242,6 @@ pub enum GetUserByNameResponse {
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
pub enum LoginUserResponse { pub enum LoginUserResponse {
/// successful operation
SuccessfulOperation { body: String, x_rate_limit: i32, x_expires_after: chrono::DateTime<chrono::Utc> } ,
/// Invalid username/password supplied /// Invalid username/password supplied
InvalidUsername , InvalidUsername ,
} }
@@ -264,103 +262,103 @@ pub enum UpdateUserResponse {
/// API /// API
pub trait Api { pub trait Api<C> {
/// To test special tags /// To test special tags
fn test_special_tags(&self, body: models::Client, context: &Context) -> Box<Future<Item=TestSpecialTagsResponse, Error=ApiError>>; fn test_special_tags(&self, client: models::Client, context: &C) -> Box<Future<Item=TestSpecialTagsResponse, Error=ApiError>>;
fn test_body_with_query_params(&self, body: models::User, query: String, context: &Context) -> Box<Future<Item=TestBodyWithQueryParamsResponse, Error=ApiError>>; fn fake_outer_boolean_serialize(&self, body: Option<bool>, context: &C) -> Box<Future<Item=FakeOuterBooleanSerializeResponse, Error=ApiError>>;
fn fake_outer_boolean_serialize(&self, body: Option<models::OuterBoolean>, context: &Context) -> Box<Future<Item=FakeOuterBooleanSerializeResponse, Error=ApiError>>; fn fake_outer_composite_serialize(&self, outer_composite: Option<models::OuterComposite>, context: &C) -> Box<Future<Item=FakeOuterCompositeSerializeResponse, Error=ApiError>>;
fn fake_outer_composite_serialize(&self, body: Option<models::OuterComposite>, context: &Context) -> Box<Future<Item=FakeOuterCompositeSerializeResponse, Error=ApiError>>; fn fake_outer_number_serialize(&self, body: Option<f64>, context: &C) -> Box<Future<Item=FakeOuterNumberSerializeResponse, Error=ApiError>>;
fn fake_outer_number_serialize(&self, body: Option<models::OuterNumber>, context: &Context) -> Box<Future<Item=FakeOuterNumberSerializeResponse, Error=ApiError>>; fn fake_outer_string_serialize(&self, body: Option<String>, context: &C) -> Box<Future<Item=FakeOuterStringSerializeResponse, Error=ApiError>>;
fn fake_outer_string_serialize(&self, body: Option<models::OuterString>, context: &Context) -> Box<Future<Item=FakeOuterStringSerializeResponse, Error=ApiError>>; fn test_body_with_query_params(&self, query: String, user: models::User, context: &C) -> Box<Future<Item=TestBodyWithQueryParamsResponse, Error=ApiError>>;
/// To test \"client\" model /// To test \"client\" model
fn test_client_model(&self, body: models::Client, context: &Context) -> Box<Future<Item=TestClientModelResponse, Error=ApiError>>; fn test_client_model(&self, client: models::Client, context: &C) -> Box<Future<Item=TestClientModelResponse, Error=ApiError>>;
/// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option<i32>, int32: Option<i32>, int64: Option<i64>, float: Option<f32>, string: Option<String>, binary: Option<swagger::ByteArray>, date: Option<chrono::DateTime<chrono::Utc>>, date_time: Option<chrono::DateTime<chrono::Utc>>, password: Option<String>, callback: Option<String>, context: &Context) -> Box<Future<Item=TestEndpointParametersResponse, Error=ApiError>>; fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, integer: Option<i32>, int32: Option<i32>, int64: Option<i64>, float: Option<f32>, string: Option<String>, binary: Box<Future<Item=Option<Box<Stream<Item=Vec<u8>, Error=Error> + Send>>, Error=Error> + Send>, date: Option<chrono::DateTime<chrono::Utc>>, date_time: Option<chrono::DateTime<chrono::Utc>>, password: Option<String>, callback: Option<String>, context: &C) -> Box<Future<Item=TestEndpointParametersResponse, Error=ApiError>>;
/// To test enum parameters /// To test enum parameters
fn test_enum_parameters(&self, enum_form_string_array: Option<&Vec<String>>, enum_form_string: Option<String>, enum_header_string_array: Option<&Vec<String>>, enum_header_string: Option<String>, enum_query_string_array: Option<&Vec<String>>, enum_query_string: Option<String>, enum_query_integer: Option<i32>, enum_query_double: Option<f64>, context: &Context) -> Box<Future<Item=TestEnumParametersResponse, Error=ApiError>>; fn test_enum_parameters(&self, enum_header_string_array: Option<&Vec<String>>, enum_header_string: Option<String>, enum_query_string_array: Option<&Vec<String>>, enum_query_string: Option<String>, enum_query_integer: Option<i32>, enum_query_double: Option<f64>, context: &C) -> Box<Future<Item=TestEnumParametersResponse, Error=ApiError>>;
/// test inline additionalProperties /// test inline additionalProperties
fn test_inline_additional_properties(&self, param: object, context: &Context) -> Box<Future<Item=TestInlineAdditionalPropertiesResponse, Error=ApiError>>; fn test_inline_additional_properties(&self, request_body: HashMap<String, String>, context: &C) -> Box<Future<Item=TestInlineAdditionalPropertiesResponse, Error=ApiError>>;
/// test json serialization of form data /// test json serialization of form data
fn test_json_form_data(&self, param: String, param2: String, context: &Context) -> Box<Future<Item=TestJsonFormDataResponse, Error=ApiError>>; fn test_json_form_data(&self, param: String, param2: String, context: &C) -> Box<Future<Item=TestJsonFormDataResponse, Error=ApiError>>;
/// To test class name in snake case /// To test class name in snake case
fn test_classname(&self, body: models::Client, context: &Context) -> Box<Future<Item=TestClassnameResponse, Error=ApiError>>; fn test_classname(&self, client: models::Client, context: &C) -> Box<Future<Item=TestClassnameResponse, Error=ApiError>>;
/// Add a new pet to the store /// Add a new pet to the store
fn add_pet(&self, body: models::Pet, context: &Context) -> Box<Future<Item=AddPetResponse, Error=ApiError>>; fn add_pet(&self, pet: models::Pet, context: &C) -> Box<Future<Item=AddPetResponse, Error=ApiError>>;
/// Deletes a pet /// Deletes a pet
fn delete_pet(&self, pet_id: i64, api_key: Option<String>, context: &Context) -> Box<Future<Item=DeletePetResponse, Error=ApiError>>; fn delete_pet(&self, pet_id: i64, api_key: Option<String>, context: &C) -> Box<Future<Item=DeletePetResponse, Error=ApiError>>;
/// Finds Pets by status /// Finds Pets by status
fn find_pets_by_status(&self, status: &Vec<String>, context: &Context) -> Box<Future<Item=FindPetsByStatusResponse, Error=ApiError>>; fn find_pets_by_status(&self, status: &Vec<String>, context: &C) -> Box<Future<Item=FindPetsByStatusResponse, Error=ApiError>>;
/// Finds Pets by tags /// Finds Pets by tags
fn find_pets_by_tags(&self, tags: &Vec<String>, context: &Context) -> Box<Future<Item=FindPetsByTagsResponse, Error=ApiError>>; fn find_pets_by_tags(&self, tags: &Vec<String>, context: &C) -> Box<Future<Item=FindPetsByTagsResponse, Error=ApiError>>;
/// Find pet by ID /// Find pet by ID
fn get_pet_by_id(&self, pet_id: i64, context: &Context) -> Box<Future<Item=GetPetByIdResponse, Error=ApiError>>; fn get_pet_by_id(&self, pet_id: i64, context: &C) -> Box<Future<Item=GetPetByIdResponse, Error=ApiError>>;
/// Update an existing pet /// Update an existing pet
fn update_pet(&self, body: models::Pet, context: &Context) -> Box<Future<Item=UpdatePetResponse, Error=ApiError>>; fn update_pet(&self, pet: models::Pet, context: &C) -> Box<Future<Item=UpdatePetResponse, Error=ApiError>>;
/// Updates a pet in the store with form data /// Updates a pet in the store with form data
fn update_pet_with_form(&self, pet_id: i64, name: Option<String>, status: Option<String>, context: &Context) -> Box<Future<Item=UpdatePetWithFormResponse, Error=ApiError>>; fn update_pet_with_form(&self, pet_id: i64, name: Option<String>, status: Option<String>, context: &C) -> Box<Future<Item=UpdatePetWithFormResponse, Error=ApiError>>;
/// uploads an image /// uploads an image
fn upload_file(&self, pet_id: i64, additional_metadata: Option<String>, file: Box<Future<Item=Option<Box<Stream<Item=Vec<u8>, Error=Error> + Send>>, Error=Error> + Send>, context: &Context) -> Box<Future<Item=UploadFileResponse, Error=ApiError>>; fn upload_file(&self, pet_id: i64, additional_metadata: Option<String>, file: Box<Future<Item=Option<Box<Stream<Item=Vec<u8>, Error=Error> + Send>>, Error=Error> + Send>, context: &C) -> Box<Future<Item=UploadFileResponse, Error=ApiError>>;
/// Delete purchase order by ID /// Delete purchase order by ID
fn delete_order(&self, order_id: String, context: &Context) -> Box<Future<Item=DeleteOrderResponse, Error=ApiError>>; fn delete_order(&self, order_id: String, context: &C) -> Box<Future<Item=DeleteOrderResponse, Error=ApiError>>;
/// Returns pet inventories by status /// Returns pet inventories by status
fn get_inventory(&self, context: &Context) -> Box<Future<Item=GetInventoryResponse, Error=ApiError>>; fn get_inventory(&self, context: &C) -> Box<Future<Item=GetInventoryResponse, Error=ApiError>>;
/// Find purchase order by ID /// Find purchase order by ID
fn get_order_by_id(&self, order_id: i64, context: &Context) -> Box<Future<Item=GetOrderByIdResponse, Error=ApiError>>; fn get_order_by_id(&self, order_id: i64, context: &C) -> Box<Future<Item=GetOrderByIdResponse, Error=ApiError>>;
/// Place an order for a pet /// Place an order for a pet
fn place_order(&self, body: models::Order, context: &Context) -> Box<Future<Item=PlaceOrderResponse, Error=ApiError>>; fn place_order(&self, order: models::Order, context: &C) -> Box<Future<Item=PlaceOrderResponse, Error=ApiError>>;
/// Create user /// Create user
fn create_user(&self, body: models::User, context: &Context) -> Box<Future<Item=CreateUserResponse, Error=ApiError>>; fn create_user(&self, user: models::User, context: &C) -> Box<Future<Item=CreateUserResponse, Error=ApiError>>;
/// Creates list of users with given input array /// Creates list of users with given input array
fn create_users_with_array_input(&self, body: &Vec<models::User>, context: &Context) -> Box<Future<Item=CreateUsersWithArrayInputResponse, Error=ApiError>>; fn create_users_with_array_input(&self, user: &Vec<models::User>, context: &C) -> Box<Future<Item=CreateUsersWithArrayInputResponse, Error=ApiError>>;
/// Creates list of users with given input array /// Creates list of users with given input array
fn create_users_with_list_input(&self, body: &Vec<models::User>, context: &Context) -> Box<Future<Item=CreateUsersWithListInputResponse, Error=ApiError>>; fn create_users_with_list_input(&self, user: &Vec<models::User>, context: &C) -> Box<Future<Item=CreateUsersWithListInputResponse, Error=ApiError>>;
/// Delete user /// Delete user
fn delete_user(&self, username: String, context: &Context) -> Box<Future<Item=DeleteUserResponse, Error=ApiError>>; fn delete_user(&self, username: String, context: &C) -> Box<Future<Item=DeleteUserResponse, Error=ApiError>>;
/// Get user by user name /// Get user by user name
fn get_user_by_name(&self, username: String, context: &Context) -> Box<Future<Item=GetUserByNameResponse, Error=ApiError>>; fn get_user_by_name(&self, username: String, context: &C) -> Box<Future<Item=GetUserByNameResponse, Error=ApiError>>;
/// Logs user into the system /// Logs user into the system
fn login_user(&self, username: String, password: String, context: &Context) -> Box<Future<Item=LoginUserResponse, Error=ApiError>>; fn login_user(&self, username: String, password: String, context: &C) -> Box<Future<Item=LoginUserResponse, Error=ApiError>>;
/// Logs out current logged in user session /// Logs out current logged in user session
fn logout_user(&self, context: &Context) -> Box<Future<Item=LogoutUserResponse, Error=ApiError>>; fn logout_user(&self, context: &C) -> Box<Future<Item=LogoutUserResponse, Error=ApiError>>;
/// Updated user /// Updated user
fn update_user(&self, username: String, body: models::User, context: &Context) -> Box<Future<Item=UpdateUserResponse, Error=ApiError>>; fn update_user(&self, username: String, user: models::User, context: &C) -> Box<Future<Item=UpdateUserResponse, Error=ApiError>>;
} }
@@ -368,43 +366,43 @@ pub trait Api {
pub trait ApiNoContext { pub trait ApiNoContext {
/// To test special tags /// To test special tags
fn test_special_tags(&self, body: models::Client) -> Box<Future<Item=TestSpecialTagsResponse, Error=ApiError>>; fn test_special_tags(&self, client: models::Client) -> Box<Future<Item=TestSpecialTagsResponse, Error=ApiError>>;
fn test_body_with_query_params(&self, body: models::User, query: String) -> Box<Future<Item=TestBodyWithQueryParamsResponse, Error=ApiError>>; fn fake_outer_boolean_serialize(&self, body: Option<bool>) -> Box<Future<Item=FakeOuterBooleanSerializeResponse, Error=ApiError>>;
fn fake_outer_boolean_serialize(&self, body: Option<models::OuterBoolean>) -> Box<Future<Item=FakeOuterBooleanSerializeResponse, Error=ApiError>>; fn fake_outer_composite_serialize(&self, outer_composite: Option<models::OuterComposite>) -> Box<Future<Item=FakeOuterCompositeSerializeResponse, Error=ApiError>>;
fn fake_outer_composite_serialize(&self, body: Option<models::OuterComposite>) -> Box<Future<Item=FakeOuterCompositeSerializeResponse, Error=ApiError>>; fn fake_outer_number_serialize(&self, body: Option<f64>) -> Box<Future<Item=FakeOuterNumberSerializeResponse, Error=ApiError>>;
fn fake_outer_number_serialize(&self, body: Option<models::OuterNumber>) -> Box<Future<Item=FakeOuterNumberSerializeResponse, Error=ApiError>>; fn fake_outer_string_serialize(&self, body: Option<String>) -> Box<Future<Item=FakeOuterStringSerializeResponse, Error=ApiError>>;
fn fake_outer_string_serialize(&self, body: Option<models::OuterString>) -> Box<Future<Item=FakeOuterStringSerializeResponse, Error=ApiError>>; fn test_body_with_query_params(&self, query: String, user: models::User) -> Box<Future<Item=TestBodyWithQueryParamsResponse, Error=ApiError>>;
/// To test \"client\" model /// To test \"client\" model
fn test_client_model(&self, body: models::Client) -> Box<Future<Item=TestClientModelResponse, Error=ApiError>>; fn test_client_model(&self, client: models::Client) -> Box<Future<Item=TestClientModelResponse, Error=ApiError>>;
/// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option<i32>, int32: Option<i32>, int64: Option<i64>, float: Option<f32>, string: Option<String>, binary: Option<swagger::ByteArray>, date: Option<chrono::DateTime<chrono::Utc>>, date_time: Option<chrono::DateTime<chrono::Utc>>, password: Option<String>, callback: Option<String>) -> Box<Future<Item=TestEndpointParametersResponse, Error=ApiError>>; fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, integer: Option<i32>, int32: Option<i32>, int64: Option<i64>, float: Option<f32>, string: Option<String>, binary: Box<Future<Item=Option<Box<Stream<Item=Vec<u8>, Error=Error> + Send>>, Error=Error> + Send>, date: Option<chrono::DateTime<chrono::Utc>>, date_time: Option<chrono::DateTime<chrono::Utc>>, password: Option<String>, callback: Option<String>) -> Box<Future<Item=TestEndpointParametersResponse, Error=ApiError>>;
/// To test enum parameters /// To test enum parameters
fn test_enum_parameters(&self, enum_form_string_array: Option<&Vec<String>>, enum_form_string: Option<String>, enum_header_string_array: Option<&Vec<String>>, enum_header_string: Option<String>, enum_query_string_array: Option<&Vec<String>>, enum_query_string: Option<String>, enum_query_integer: Option<i32>, enum_query_double: Option<f64>) -> Box<Future<Item=TestEnumParametersResponse, Error=ApiError>>; fn test_enum_parameters(&self, enum_header_string_array: Option<&Vec<String>>, enum_header_string: Option<String>, enum_query_string_array: Option<&Vec<String>>, enum_query_string: Option<String>, enum_query_integer: Option<i32>, enum_query_double: Option<f64>) -> Box<Future<Item=TestEnumParametersResponse, Error=ApiError>>;
/// test inline additionalProperties /// test inline additionalProperties
fn test_inline_additional_properties(&self, param: object) -> Box<Future<Item=TestInlineAdditionalPropertiesResponse, Error=ApiError>>; fn test_inline_additional_properties(&self, request_body: HashMap<String, String>) -> Box<Future<Item=TestInlineAdditionalPropertiesResponse, Error=ApiError>>;
/// test json serialization of form data /// test json serialization of form data
fn test_json_form_data(&self, param: String, param2: String) -> Box<Future<Item=TestJsonFormDataResponse, Error=ApiError>>; fn test_json_form_data(&self, param: String, param2: String) -> Box<Future<Item=TestJsonFormDataResponse, Error=ApiError>>;
/// To test class name in snake case /// To test class name in snake case
fn test_classname(&self, body: models::Client) -> Box<Future<Item=TestClassnameResponse, Error=ApiError>>; fn test_classname(&self, client: models::Client) -> Box<Future<Item=TestClassnameResponse, Error=ApiError>>;
/// Add a new pet to the store /// Add a new pet to the store
fn add_pet(&self, body: models::Pet) -> Box<Future<Item=AddPetResponse, Error=ApiError>>; fn add_pet(&self, pet: models::Pet) -> Box<Future<Item=AddPetResponse, Error=ApiError>>;
/// Deletes a pet /// Deletes a pet
fn delete_pet(&self, pet_id: i64, api_key: Option<String>) -> Box<Future<Item=DeletePetResponse, Error=ApiError>>; fn delete_pet(&self, pet_id: i64, api_key: Option<String>) -> Box<Future<Item=DeletePetResponse, Error=ApiError>>;
@@ -419,7 +417,7 @@ pub trait ApiNoContext {
fn get_pet_by_id(&self, pet_id: i64) -> Box<Future<Item=GetPetByIdResponse, Error=ApiError>>; fn get_pet_by_id(&self, pet_id: i64) -> Box<Future<Item=GetPetByIdResponse, Error=ApiError>>;
/// Update an existing pet /// Update an existing pet
fn update_pet(&self, body: models::Pet) -> Box<Future<Item=UpdatePetResponse, Error=ApiError>>; fn update_pet(&self, pet: models::Pet) -> Box<Future<Item=UpdatePetResponse, Error=ApiError>>;
/// Updates a pet in the store with form data /// Updates a pet in the store with form data
fn update_pet_with_form(&self, pet_id: i64, name: Option<String>, status: Option<String>) -> Box<Future<Item=UpdatePetWithFormResponse, Error=ApiError>>; fn update_pet_with_form(&self, pet_id: i64, name: Option<String>, status: Option<String>) -> Box<Future<Item=UpdatePetWithFormResponse, Error=ApiError>>;
@@ -437,16 +435,16 @@ pub trait ApiNoContext {
fn get_order_by_id(&self, order_id: i64) -> Box<Future<Item=GetOrderByIdResponse, Error=ApiError>>; fn get_order_by_id(&self, order_id: i64) -> Box<Future<Item=GetOrderByIdResponse, Error=ApiError>>;
/// Place an order for a pet /// Place an order for a pet
fn place_order(&self, body: models::Order) -> Box<Future<Item=PlaceOrderResponse, Error=ApiError>>; fn place_order(&self, order: models::Order) -> Box<Future<Item=PlaceOrderResponse, Error=ApiError>>;
/// Create user /// Create user
fn create_user(&self, body: models::User) -> Box<Future<Item=CreateUserResponse, Error=ApiError>>; fn create_user(&self, user: models::User) -> Box<Future<Item=CreateUserResponse, Error=ApiError>>;
/// Creates list of users with given input array /// Creates list of users with given input array
fn create_users_with_array_input(&self, body: &Vec<models::User>) -> Box<Future<Item=CreateUsersWithArrayInputResponse, Error=ApiError>>; fn create_users_with_array_input(&self, user: &Vec<models::User>) -> Box<Future<Item=CreateUsersWithArrayInputResponse, Error=ApiError>>;
/// Creates list of users with given input array /// Creates list of users with given input array
fn create_users_with_list_input(&self, body: &Vec<models::User>) -> Box<Future<Item=CreateUsersWithListInputResponse, Error=ApiError>>; fn create_users_with_list_input(&self, user: &Vec<models::User>) -> Box<Future<Item=CreateUsersWithListInputResponse, Error=ApiError>>;
/// Delete user /// Delete user
fn delete_user(&self, username: String) -> Box<Future<Item=DeleteUserResponse, Error=ApiError>>; fn delete_user(&self, username: String) -> Box<Future<Item=DeleteUserResponse, Error=ApiError>>;
@@ -461,72 +459,72 @@ pub trait ApiNoContext {
fn logout_user(&self) -> Box<Future<Item=LogoutUserResponse, Error=ApiError>>; fn logout_user(&self) -> Box<Future<Item=LogoutUserResponse, Error=ApiError>>;
/// Updated user /// Updated user
fn update_user(&self, username: String, body: models::User) -> Box<Future<Item=UpdateUserResponse, Error=ApiError>>; fn update_user(&self, username: String, user: models::User) -> Box<Future<Item=UpdateUserResponse, Error=ApiError>>;
} }
/// Trait to extend an API to make it easy to bind it to a context. /// Trait to extend an API to make it easy to bind it to a context.
pub trait ContextWrapperExt<'a> where Self: Sized { pub trait ContextWrapperExt<'a, C> where Self: Sized {
/// Binds this API to a context. /// Binds this API to a context.
fn with_context(self: &'a Self, context: Context) -> ContextWrapper<'a, Self>; fn with_context(self: &'a Self, context: C) -> ContextWrapper<'a, Self, C>;
} }
impl<'a, T: Api + Sized> ContextWrapperExt<'a> for T { impl<'a, T: Api<C> + Sized, C> ContextWrapperExt<'a, C> for T {
fn with_context(self: &'a T, context: Context) -> ContextWrapper<'a, T> { fn with_context(self: &'a T, context: C) -> ContextWrapper<'a, T, C> {
ContextWrapper::<T>::new(self, context) ContextWrapper::<T, C>::new(self, context)
} }
} }
impl<'a, T: Api> ApiNoContext for ContextWrapper<'a, T> { impl<'a, T: Api<C>, C> ApiNoContext for ContextWrapper<'a, T, C> {
/// To test special tags /// To test special tags
fn test_special_tags(&self, body: models::Client) -> Box<Future<Item=TestSpecialTagsResponse, Error=ApiError>> { fn test_special_tags(&self, client: models::Client) -> Box<Future<Item=TestSpecialTagsResponse, Error=ApiError>> {
self.api().test_special_tags(body, &self.context()) self.api().test_special_tags(client, &self.context())
} }
fn test_body_with_query_params(&self, body: models::User, query: String) -> Box<Future<Item=TestBodyWithQueryParamsResponse, Error=ApiError>> { fn fake_outer_boolean_serialize(&self, body: Option<bool>) -> Box<Future<Item=FakeOuterBooleanSerializeResponse, Error=ApiError>> {
self.api().test_body_with_query_params(body, query, &self.context())
}
fn fake_outer_boolean_serialize(&self, body: Option<models::OuterBoolean>) -> Box<Future<Item=FakeOuterBooleanSerializeResponse, Error=ApiError>> {
self.api().fake_outer_boolean_serialize(body, &self.context()) self.api().fake_outer_boolean_serialize(body, &self.context())
} }
fn fake_outer_composite_serialize(&self, body: Option<models::OuterComposite>) -> Box<Future<Item=FakeOuterCompositeSerializeResponse, Error=ApiError>> { fn fake_outer_composite_serialize(&self, outer_composite: Option<models::OuterComposite>) -> Box<Future<Item=FakeOuterCompositeSerializeResponse, Error=ApiError>> {
self.api().fake_outer_composite_serialize(body, &self.context()) self.api().fake_outer_composite_serialize(outer_composite, &self.context())
} }
fn fake_outer_number_serialize(&self, body: Option<models::OuterNumber>) -> Box<Future<Item=FakeOuterNumberSerializeResponse, Error=ApiError>> { fn fake_outer_number_serialize(&self, body: Option<f64>) -> Box<Future<Item=FakeOuterNumberSerializeResponse, Error=ApiError>> {
self.api().fake_outer_number_serialize(body, &self.context()) self.api().fake_outer_number_serialize(body, &self.context())
} }
fn fake_outer_string_serialize(&self, body: Option<models::OuterString>) -> Box<Future<Item=FakeOuterStringSerializeResponse, Error=ApiError>> { fn fake_outer_string_serialize(&self, body: Option<String>) -> Box<Future<Item=FakeOuterStringSerializeResponse, Error=ApiError>> {
self.api().fake_outer_string_serialize(body, &self.context()) self.api().fake_outer_string_serialize(body, &self.context())
} }
fn test_body_with_query_params(&self, query: String, user: models::User) -> Box<Future<Item=TestBodyWithQueryParamsResponse, Error=ApiError>> {
self.api().test_body_with_query_params(query, user, &self.context())
}
/// To test \"client\" model /// To test \"client\" model
fn test_client_model(&self, body: models::Client) -> Box<Future<Item=TestClientModelResponse, Error=ApiError>> { fn test_client_model(&self, client: models::Client) -> Box<Future<Item=TestClientModelResponse, Error=ApiError>> {
self.api().test_client_model(body, &self.context()) self.api().test_client_model(client, &self.context())
} }
/// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option<i32>, int32: Option<i32>, int64: Option<i64>, float: Option<f32>, string: Option<String>, binary: Option<swagger::ByteArray>, date: Option<chrono::DateTime<chrono::Utc>>, date_time: Option<chrono::DateTime<chrono::Utc>>, password: Option<String>, callback: Option<String>) -> Box<Future<Item=TestEndpointParametersResponse, Error=ApiError>> { fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, integer: Option<i32>, int32: Option<i32>, int64: Option<i64>, float: Option<f32>, string: Option<String>, binary: Box<Future<Item=Option<Box<Stream<Item=Vec<u8>, Error=Error> + Send>>, Error=Error> + Send>, date: Option<chrono::DateTime<chrono::Utc>>, date_time: Option<chrono::DateTime<chrono::Utc>>, password: Option<String>, callback: Option<String>) -> Box<Future<Item=TestEndpointParametersResponse, Error=ApiError>> {
self.api().test_endpoint_parameters(number, double, pattern_without_delimiter, byte, integer, int32, int64, float, string, binary, date, date_time, password, callback, &self.context()) self.api().test_endpoint_parameters(number, double, pattern_without_delimiter, integer, int32, int64, float, string, binary, date, date_time, password, callback, &self.context())
} }
/// To test enum parameters /// To test enum parameters
fn test_enum_parameters(&self, enum_form_string_array: Option<&Vec<String>>, enum_form_string: Option<String>, enum_header_string_array: Option<&Vec<String>>, enum_header_string: Option<String>, enum_query_string_array: Option<&Vec<String>>, enum_query_string: Option<String>, enum_query_integer: Option<i32>, enum_query_double: Option<f64>) -> Box<Future<Item=TestEnumParametersResponse, Error=ApiError>> { fn test_enum_parameters(&self, enum_header_string_array: Option<&Vec<String>>, enum_header_string: Option<String>, enum_query_string_array: Option<&Vec<String>>, enum_query_string: Option<String>, enum_query_integer: Option<i32>, enum_query_double: Option<f64>) -> Box<Future<Item=TestEnumParametersResponse, Error=ApiError>> {
self.api().test_enum_parameters(enum_form_string_array, enum_form_string, enum_header_string_array, enum_header_string, enum_query_string_array, enum_query_string, enum_query_integer, enum_query_double, &self.context()) self.api().test_enum_parameters(enum_header_string_array, enum_header_string, enum_query_string_array, enum_query_string, enum_query_integer, enum_query_double, &self.context())
} }
/// test inline additionalProperties /// test inline additionalProperties
fn test_inline_additional_properties(&self, param: object) -> Box<Future<Item=TestInlineAdditionalPropertiesResponse, Error=ApiError>> { fn test_inline_additional_properties(&self, request_body: HashMap<String, String>) -> Box<Future<Item=TestInlineAdditionalPropertiesResponse, Error=ApiError>> {
self.api().test_inline_additional_properties(param, &self.context()) self.api().test_inline_additional_properties(request_body, &self.context())
} }
/// test json serialization of form data /// test json serialization of form data
@@ -535,13 +533,13 @@ impl<'a, T: Api> ApiNoContext for ContextWrapper<'a, T> {
} }
/// To test class name in snake case /// To test class name in snake case
fn test_classname(&self, body: models::Client) -> Box<Future<Item=TestClassnameResponse, Error=ApiError>> { fn test_classname(&self, client: models::Client) -> Box<Future<Item=TestClassnameResponse, Error=ApiError>> {
self.api().test_classname(body, &self.context()) self.api().test_classname(client, &self.context())
} }
/// Add a new pet to the store /// Add a new pet to the store
fn add_pet(&self, body: models::Pet) -> Box<Future<Item=AddPetResponse, Error=ApiError>> { fn add_pet(&self, pet: models::Pet) -> Box<Future<Item=AddPetResponse, Error=ApiError>> {
self.api().add_pet(body, &self.context()) self.api().add_pet(pet, &self.context())
} }
/// Deletes a pet /// Deletes a pet
@@ -565,8 +563,8 @@ impl<'a, T: Api> ApiNoContext for ContextWrapper<'a, T> {
} }
/// Update an existing pet /// Update an existing pet
fn update_pet(&self, body: models::Pet) -> Box<Future<Item=UpdatePetResponse, Error=ApiError>> { fn update_pet(&self, pet: models::Pet) -> Box<Future<Item=UpdatePetResponse, Error=ApiError>> {
self.api().update_pet(body, &self.context()) self.api().update_pet(pet, &self.context())
} }
/// Updates a pet in the store with form data /// Updates a pet in the store with form data
@@ -595,23 +593,23 @@ impl<'a, T: Api> ApiNoContext for ContextWrapper<'a, T> {
} }
/// Place an order for a pet /// Place an order for a pet
fn place_order(&self, body: models::Order) -> Box<Future<Item=PlaceOrderResponse, Error=ApiError>> { fn place_order(&self, order: models::Order) -> Box<Future<Item=PlaceOrderResponse, Error=ApiError>> {
self.api().place_order(body, &self.context()) self.api().place_order(order, &self.context())
} }
/// Create user /// Create user
fn create_user(&self, body: models::User) -> Box<Future<Item=CreateUserResponse, Error=ApiError>> { fn create_user(&self, user: models::User) -> Box<Future<Item=CreateUserResponse, Error=ApiError>> {
self.api().create_user(body, &self.context()) self.api().create_user(user, &self.context())
} }
/// Creates list of users with given input array /// Creates list of users with given input array
fn create_users_with_array_input(&self, body: &Vec<models::User>) -> Box<Future<Item=CreateUsersWithArrayInputResponse, Error=ApiError>> { fn create_users_with_array_input(&self, user: &Vec<models::User>) -> Box<Future<Item=CreateUsersWithArrayInputResponse, Error=ApiError>> {
self.api().create_users_with_array_input(body, &self.context()) self.api().create_users_with_array_input(user, &self.context())
} }
/// Creates list of users with given input array /// Creates list of users with given input array
fn create_users_with_list_input(&self, body: &Vec<models::User>) -> Box<Future<Item=CreateUsersWithListInputResponse, Error=ApiError>> { fn create_users_with_list_input(&self, user: &Vec<models::User>) -> Box<Future<Item=CreateUsersWithListInputResponse, Error=ApiError>> {
self.api().create_users_with_list_input(body, &self.context()) self.api().create_users_with_list_input(user, &self.context())
} }
/// Delete user /// Delete user
@@ -635,8 +633,8 @@ impl<'a, T: Api> ApiNoContext for ContextWrapper<'a, T> {
} }
/// Updated user /// Updated user
fn update_user(&self, username: String, body: models::User) -> Box<Future<Item=UpdateUserResponse, Error=ApiError>> { fn update_user(&self, username: String, user: models::User) -> Box<Future<Item=UpdateUserResponse, Error=ApiError>> {
self.api().update_user(username, body, &self.context()) self.api().update_user(username, user, &self.context())
} }
} }

View File

@@ -8,6 +8,22 @@ pub mod responses {
lazy_static! { lazy_static! {
pub static ref TEST_SPECIAL_TAGS_SUCCESSFUL_OPERATION: Mime = "application/json".parse().unwrap(); pub static ref TEST_SPECIAL_TAGS_SUCCESSFUL_OPERATION: Mime = "application/json".parse().unwrap();
} }
/// Create Mime objects for the response content types for FakeOuterBooleanSerialize
lazy_static! {
pub static ref FAKE_OUTER_BOOLEAN_SERIALIZE_OUTPUT_BOOLEAN: Mime = "*/*".parse().unwrap();
}
/// Create Mime objects for the response content types for FakeOuterCompositeSerialize
lazy_static! {
pub static ref FAKE_OUTER_COMPOSITE_SERIALIZE_OUTPUT_COMPOSITE: Mime = "*/*".parse().unwrap();
}
/// Create Mime objects for the response content types for FakeOuterNumberSerialize
lazy_static! {
pub static ref FAKE_OUTER_NUMBER_SERIALIZE_OUTPUT_NUMBER: Mime = "*/*".parse().unwrap();
}
/// Create Mime objects for the response content types for FakeOuterStringSerialize
lazy_static! {
pub static ref FAKE_OUTER_STRING_SERIALIZE_OUTPUT_STRING: Mime = "*/*".parse().unwrap();
}
/// Create Mime objects for the response content types for TestClientModel /// Create Mime objects for the response content types for TestClientModel
lazy_static! { lazy_static! {
pub static ref TEST_CLIENT_MODEL_SUCCESSFUL_OPERATION: Mime = "application/json".parse().unwrap(); pub static ref TEST_CLIENT_MODEL_SUCCESSFUL_OPERATION: Mime = "application/json".parse().unwrap();
@@ -18,15 +34,15 @@ pub mod responses {
} }
/// Create Mime objects for the response content types for FindPetsByStatus /// Create Mime objects for the response content types for FindPetsByStatus
lazy_static! { lazy_static! {
pub static ref FIND_PETS_BY_STATUS_SUCCESSFUL_OPERATION: Mime = "application/xml".parse().unwrap(); pub static ref FIND_PETS_BY_STATUS_SUCCESSFUL_OPERATION: Mime = "application/json".parse().unwrap();
} }
/// Create Mime objects for the response content types for FindPetsByTags /// Create Mime objects for the response content types for FindPetsByTags
lazy_static! { lazy_static! {
pub static ref FIND_PETS_BY_TAGS_SUCCESSFUL_OPERATION: Mime = "application/xml".parse().unwrap(); pub static ref FIND_PETS_BY_TAGS_SUCCESSFUL_OPERATION: Mime = "application/json".parse().unwrap();
} }
/// Create Mime objects for the response content types for GetPetById /// Create Mime objects for the response content types for GetPetById
lazy_static! { lazy_static! {
pub static ref GET_PET_BY_ID_SUCCESSFUL_OPERATION: Mime = "application/xml".parse().unwrap(); pub static ref GET_PET_BY_ID_SUCCESSFUL_OPERATION: Mime = "application/json".parse().unwrap();
} }
/// Create Mime objects for the response content types for UploadFile /// Create Mime objects for the response content types for UploadFile
lazy_static! { lazy_static! {
@@ -38,19 +54,15 @@ pub mod responses {
} }
/// Create Mime objects for the response content types for GetOrderById /// Create Mime objects for the response content types for GetOrderById
lazy_static! { lazy_static! {
pub static ref GET_ORDER_BY_ID_SUCCESSFUL_OPERATION: Mime = "application/xml".parse().unwrap(); pub static ref GET_ORDER_BY_ID_SUCCESSFUL_OPERATION: Mime = "application/json".parse().unwrap();
} }
/// Create Mime objects for the response content types for PlaceOrder /// Create Mime objects for the response content types for PlaceOrder
lazy_static! { lazy_static! {
pub static ref PLACE_ORDER_SUCCESSFUL_OPERATION: Mime = "application/xml".parse().unwrap(); pub static ref PLACE_ORDER_SUCCESSFUL_OPERATION: Mime = "application/json".parse().unwrap();
} }
/// Create Mime objects for the response content types for GetUserByName /// Create Mime objects for the response content types for GetUserByName
lazy_static! { lazy_static! {
pub static ref GET_USER_BY_NAME_SUCCESSFUL_OPERATION: Mime = "application/xml".parse().unwrap(); pub static ref GET_USER_BY_NAME_SUCCESSFUL_OPERATION: Mime = "application/json".parse().unwrap();
}
/// Create Mime objects for the response content types for LoginUser
lazy_static! {
pub static ref LOGIN_USER_SUCCESSFUL_OPERATION: Mime = "application/xml".parse().unwrap();
} }
} }
@@ -61,10 +73,6 @@ pub mod requests {
lazy_static! { lazy_static! {
pub static ref TEST_SPECIAL_TAGS: Mime = "application/json".parse().unwrap(); pub static ref TEST_SPECIAL_TAGS: Mime = "application/json".parse().unwrap();
} }
/// Create Mime objects for the request content types for TestBodyWithQueryParams
lazy_static! {
pub static ref TEST_BODY_WITH_QUERY_PARAMS: Mime = "application/json".parse().unwrap();
}
/// Create Mime objects for the request content types for FakeOuterBooleanSerialize /// Create Mime objects for the request content types for FakeOuterBooleanSerialize
lazy_static! { lazy_static! {
pub static ref FAKE_OUTER_BOOLEAN_SERIALIZE: Mime = "application/json".parse().unwrap(); pub static ref FAKE_OUTER_BOOLEAN_SERIALIZE: Mime = "application/json".parse().unwrap();
@@ -81,25 +89,21 @@ pub mod requests {
lazy_static! { lazy_static! {
pub static ref FAKE_OUTER_STRING_SERIALIZE: Mime = "application/json".parse().unwrap(); pub static ref FAKE_OUTER_STRING_SERIALIZE: Mime = "application/json".parse().unwrap();
} }
/// Create Mime objects for the request content types for TestBodyWithQueryParams
lazy_static! {
pub static ref TEST_BODY_WITH_QUERY_PARAMS: Mime = "application/json".parse().unwrap();
}
/// Create Mime objects for the request content types for TestClientModel /// Create Mime objects for the request content types for TestClientModel
lazy_static! { lazy_static! {
pub static ref TEST_CLIENT_MODEL: Mime = "application/json".parse().unwrap(); pub static ref TEST_CLIENT_MODEL: Mime = "application/json".parse().unwrap();
} }
/// Create Mime objects for the request content types for TestEndpointParameters
lazy_static! {
pub static ref TEST_ENDPOINT_PARAMETERS: Mime = "application/xml; charset=utf-8".parse().unwrap();
}
/// Create Mime objects for the request content types for TestEnumParameters
lazy_static! {
pub static ref TEST_ENUM_PARAMETERS: Mime = "*/*".parse().unwrap();
}
/// Create Mime objects for the request content types for TestInlineAdditionalProperties /// Create Mime objects for the request content types for TestInlineAdditionalProperties
lazy_static! { lazy_static! {
pub static ref TEST_INLINE_ADDITIONAL_PROPERTIES: Mime = "application/json".parse().unwrap(); pub static ref TEST_INLINE_ADDITIONAL_PROPERTIES: Mime = "application/json".parse().unwrap();
} }
/// Create Mime objects for the request content types for TestJsonFormData /// Create Mime objects for the request content types for TestJsonFormData
lazy_static! { lazy_static! {
pub static ref TEST_JSON_FORM_DATA: Mime = "application/json".parse().unwrap(); pub static ref TEST_JSON_FORM_DATA: Mime = "application/x-www-form-urlencoded".parse().unwrap();
} }
/// Create Mime objects for the request content types for TestClassname /// Create Mime objects for the request content types for TestClassname
lazy_static! { lazy_static! {

View File

@@ -239,6 +239,31 @@ impl Capitalization {
} }
} }
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Cat {
#[serde(rename = "className")]
pub class_name: String,
#[serde(rename = "color")]
#[serde(skip_serializing_if="Option::is_none")]
pub color: Option<String>,
#[serde(rename = "declawed")]
#[serde(skip_serializing_if="Option::is_none")]
pub declawed: Option<bool>,
}
impl Cat {
pub fn new(class_name: String, ) -> Cat {
Cat {
class_name: class_name,
color: Some("red".to_string()),
declawed: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename = "Category")] #[serde(rename = "Category")]
pub struct Category { pub struct Category {
@@ -294,14 +319,39 @@ impl Client {
} }
} }
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Dog {
#[serde(rename = "className")]
pub class_name: String,
#[serde(rename = "color")]
#[serde(skip_serializing_if="Option::is_none")]
pub color: Option<String>,
#[serde(rename = "breed")]
#[serde(skip_serializing_if="Option::is_none")]
pub breed: Option<String>,
}
impl Dog {
pub fn new(class_name: String, ) -> Dog {
Dog {
class_name: class_name,
color: Some("red".to_string()),
breed: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EnumArrays { pub struct EnumArrays {
// Note: inline enums are not fully supported by swagger-codegen // Note: inline enums are not fully supported by openapi-generator
#[serde(rename = "just_symbol")] #[serde(rename = "just_symbol")]
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if="Option::is_none")]
pub just_symbol: Option<String>, pub just_symbol: Option<String>,
// Note: inline enums are not fully supported by swagger-codegen // Note: inline enums are not fully supported by openapi-generator
#[serde(rename = "array_enum")] #[serde(rename = "array_enum")]
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if="Option::is_none")]
pub array_enum: Option<Vec<String>>, pub array_enum: Option<Vec<String>>,
@@ -356,21 +406,21 @@ impl ::std::str::FromStr for EnumClass {
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EnumTest { pub struct EnumTest {
// Note: inline enums are not fully supported by swagger-codegen // Note: inline enums are not fully supported by openapi-generator
#[serde(rename = "enum_string")] #[serde(rename = "enum_string")]
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if="Option::is_none")]
pub enum_string: Option<String>, pub enum_string: Option<String>,
// Note: inline enums are not fully supported by swagger-codegen // Note: inline enums are not fully supported by openapi-generator
#[serde(rename = "enum_string_required")] #[serde(rename = "enum_string_required")]
pub enum_string_required: String, pub enum_string_required: String,
// Note: inline enums are not fully supported by swagger-codegen // Note: inline enums are not fully supported by openapi-generator
#[serde(rename = "enum_integer")] #[serde(rename = "enum_integer")]
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if="Option::is_none")]
pub enum_integer: Option<i32>, pub enum_integer: Option<i32>,
// Note: inline enums are not fully supported by swagger-codegen // Note: inline enums are not fully supported by openapi-generator
#[serde(rename = "enum_number")] #[serde(rename = "enum_number")]
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if="Option::is_none")]
pub enum_number: Option<f64>, pub enum_number: Option<f64>,
@@ -425,10 +475,6 @@ pub struct FormatTest {
#[serde(rename = "byte")] #[serde(rename = "byte")]
pub byte: swagger::ByteArray, pub byte: swagger::ByteArray,
#[serde(rename = "binary")]
#[serde(skip_serializing_if="Option::is_none")]
pub binary: Option<swagger::ByteArray>,
#[serde(rename = "date")] #[serde(rename = "date")]
pub date: chrono::DateTime<chrono::Utc>, pub date: chrono::DateTime<chrono::Utc>,
@@ -456,7 +502,6 @@ impl FormatTest {
double: None, double: None,
string: None, string: None,
byte: byte, byte: byte,
binary: None,
date: date, date: date,
date_time: None, date_time: None,
uuid: None, uuid: None,
@@ -508,7 +553,7 @@ pub struct MapTest {
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if="Option::is_none")]
pub map_map_of_string: Option<HashMap<String, HashMap<String, String>>>, pub map_map_of_string: Option<HashMap<String, HashMap<String, String>>>,
// Note: inline enums are not fully supported by swagger-codegen // Note: inline enums are not fully supported by openapi-generator
#[serde(rename = "map_of_enum_string")] #[serde(rename = "map_of_enum_string")]
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if="Option::is_none")]
pub map_of_enum_string: Option<HashMap<String, String>>, pub map_of_enum_string: Option<HashMap<String, String>>,
@@ -659,7 +704,7 @@ pub struct Order {
pub ship_date: Option<chrono::DateTime<chrono::Utc>>, pub ship_date: Option<chrono::DateTime<chrono::Utc>>,
/// Order Status /// Order Status
// Note: inline enums are not fully supported by swagger-codegen // Note: inline enums are not fully supported by openapi-generator
#[serde(rename = "status")] #[serde(rename = "status")]
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if="Option::is_none")]
pub status: Option<String>, pub status: Option<String>,
@@ -858,7 +903,7 @@ pub struct Pet {
pub tags: Option<Vec<models::Tag>>, pub tags: Option<Vec<models::Tag>>,
/// pet status in the store /// pet status in the store
// Note: inline enums are not fully supported by swagger-codegen // Note: inline enums are not fully supported by openapi-generator
#[serde(rename = "status")] #[serde(rename = "status")]
#[serde(skip_serializing_if="Option::is_none")] #[serde(skip_serializing_if="Option::is_none")]
pub status: Option<String>, pub status: Option<String>,
@@ -990,53 +1035,3 @@ impl User {
} }
} }
} }
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Cat {
#[serde(rename = "className")]
pub class_name: String,
#[serde(rename = "color")]
#[serde(skip_serializing_if="Option::is_none")]
pub color: Option<String>,
#[serde(rename = "declawed")]
#[serde(skip_serializing_if="Option::is_none")]
pub declawed: Option<bool>,
}
impl Cat {
pub fn new(class_name: String, ) -> Cat {
Cat {
class_name: class_name,
color: Some("red".to_string()),
declawed: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Dog {
#[serde(rename = "className")]
pub class_name: String,
#[serde(rename = "color")]
#[serde(skip_serializing_if="Option::is_none")]
pub color: Option<String>,
#[serde(rename = "breed")]
#[serde(skip_serializing_if="Option::is_none")]
pub breed: Option<String>,
}
impl Dog {
pub fn new(class_name: String, ) -> Dog {
Dog {
class_name: class_name,
color: Some("red".to_string()),
breed: None,
}
}
}

View File

@@ -1,25 +1,47 @@
use std::io; use std::io;
use std::marker::PhantomData;
use std::default::Default;
use hyper; use hyper;
use hyper::{Request, Response, Error, StatusCode}; use hyper::{Request, Response, Error, StatusCode};
use server::url::form_urlencoded; use server::url::form_urlencoded;
use swagger::auth::{Authorization, AuthData, Scopes}; use swagger::auth::{Authorization, AuthData, Scopes};
use swagger::{Has, Pop, Push, XSpanIdString};
use Api; use Api;
pub struct NewService<T> where T: hyper::server::NewService<Request=(Request,Option<AuthData>), Response=Response, Error=Error> { pub struct NewService<T, C>
where
C: Default + Push<XSpanIdString>,
C::Result: Push<Option<AuthData>>,
T: hyper::server::NewService<Request = (Request, <C::Result as Push<Option<AuthData>>>::Result), Response = Response, Error = Error>,
{
inner: T, inner: T,
marker: PhantomData<C>,
} }
impl<T> NewService<T> where T: hyper::server::NewService<Request=(Request,Option<AuthData>), Response=Response, Error=Error> + 'static { impl<T, C> NewService<T, C>
pub fn new(inner: T) -> NewService<T> { where
NewService{inner} C: Default + Push<XSpanIdString>,
C::Result: Push<Option<AuthData>>,
T: hyper::server::NewService<Request = (Request, <C::Result as Push<Option<AuthData>>>::Result), Response = Response, Error = Error> + 'static,
{
pub fn new(inner: T) -> NewService<T, C> {
NewService {
inner,
marker: PhantomData,
}
} }
} }
impl<T> hyper::server::NewService for NewService<T> where T: hyper::server::NewService<Request=(Request,Option<AuthData>), Response=Response, Error=Error> + 'static { impl<T, C> hyper::server::NewService for NewService<T, C>
where
C: Default + Push<XSpanIdString>,
C::Result: Push<Option<AuthData>>,
T: hyper::server::NewService<Request = (Request, <C::Result as Push<Option<AuthData>>>::Result), Response = Response, Error = Error> + 'static,
{
type Request = Request; type Request = Request;
type Response = Response; type Response = Response;
type Error = Error; type Error = Error;
type Instance = Service<T::Instance>; type Instance = Service<T::Instance, C>;
fn new_service(&self) -> Result<Self::Instance, io::Error> { fn new_service(&self) -> Result<Self::Instance, io::Error> {
self.inner.new_service().map(|s| Service::new(s)) self.inner.new_service().map(|s| Service::new(s))
@@ -27,28 +49,50 @@ impl<T> hyper::server::NewService for NewService<T> where T: hyper::server::NewS
} }
/// Middleware to extract authentication data from request /// Middleware to extract authentication data from request
pub struct Service<T> where T: hyper::server::Service<Request=(Request,Option<AuthData>), Response=Response, Error=Error> { pub struct Service<T, C>
where
C: Default + Push<XSpanIdString>,
C::Result: Push<Option<AuthData>>,
T: hyper::server::Service<Request = (Request, <C::Result as Push<Option<AuthData>>>::Result), Response = Response, Error = Error>,
{
inner: T, inner: T,
marker: PhantomData<C>,
} }
impl<T> Service<T> where T: hyper::server::Service<Request=(Request,Option<AuthData>), Response=Response, Error=Error> { impl<T, C> Service<T, C>
pub fn new(inner: T) -> Service<T> { where
Service{inner} C: Default + Push<XSpanIdString>,
C::Result: Push<Option<AuthData>>,
T: hyper::server::Service<Request = (Request, <C::Result as Push<Option<AuthData>>>::Result), Response = Response, Error = Error>,
{
pub fn new(inner: T) -> Service<T, C> {
Service {
inner,
marker: PhantomData,
}
} }
} }
impl<T> hyper::server::Service for Service<T> where T: hyper::server::Service<Request=(Request,Option<AuthData>), Response=Response, Error=Error> { impl<T, C> hyper::server::Service for Service<T, C>
where
C: Default + Push<XSpanIdString>,
C::Result: Push<Option<AuthData>>,
T: hyper::server::Service<Request = (Request, <C::Result as Push<Option<AuthData>>>::Result), Response = Response, Error = Error>,
{
type Request = Request; type Request = Request;
type Response = Response; type Response = Response;
type Error = Error; type Error = Error;
type Future = T::Future; type Future = T::Future;
fn call(&self, req: Self::Request) -> Self::Future { fn call(&self, req: Self::Request) -> Self::Future {
let context = C::default().push(XSpanIdString::get_or_generate(&req));
{ {
header! { (ApiKey1, "api_key") => [String] } header! { (ApiKey1, "api_key") => [String] }
if let Some(header) = req.headers().get::<ApiKey1>().cloned() { if let Some(header) = req.headers().get::<ApiKey1>().cloned() {
let auth_data = AuthData::ApiKey(header.0); let auth_data = AuthData::ApiKey(header.0);
return self.inner.call((req, Some(auth_data))); let context = context.push(Some(auth_data));
return self.inner.call((req, context));
} }
} }
{ {
@@ -58,7 +102,8 @@ impl<T> hyper::server::Service for Service<T> where T: hyper::server::Service<Re
.nth(0); .nth(0);
if let Some(key) = key { if let Some(key) = key {
let auth_data = AuthData::ApiKey(key); let auth_data = AuthData::ApiKey(key);
return self.inner.call((req, Some(auth_data))); let context = context.push(Some(auth_data));
return self.inner.call((req, context));
} }
} }
{ {
@@ -66,7 +111,8 @@ impl<T> hyper::server::Service for Service<T> where T: hyper::server::Service<Re
use std::ops::Deref; use std::ops::Deref;
if let Some(basic) = req.headers().get::<Authorization<Basic>>().cloned() { if let Some(basic) = req.headers().get::<Authorization<Basic>>().cloned() {
let auth_data = AuthData::Basic(basic.deref().clone()); let auth_data = AuthData::Basic(basic.deref().clone());
return self.inner.call((req, Some(auth_data))); let context = context.push(Some(auth_data));
return self.inner.call((req, context));
} }
} }
{ {
@@ -74,10 +120,12 @@ impl<T> hyper::server::Service for Service<T> where T: hyper::server::Service<Re
use std::ops::Deref; use std::ops::Deref;
if let Some(bearer) = req.headers().get::<Authorization<Bearer>>().cloned() { if let Some(bearer) = req.headers().get::<Authorization<Bearer>>().cloned() {
let auth_data = AuthData::Bearer(bearer.deref().clone()); let auth_data = AuthData::Bearer(bearer.deref().clone());
return self.inner.call((req, Some(auth_data))); let context = context.push(Some(auth_data));
return self.inner.call((req, context));
} }
} }
return self.inner.call((req, None)); let context = context.push(None);
return self.inner.call((req, context));
} }
} }

File diff suppressed because it is too large Load Diff