[Core, Rust Server] anyOf / oneOf support for Rust Server (#6690)

* [Core] Inline Model Resolution of Enums

Enums need to be named types, so handle them as part of inline model resolution

* [Rust Server] Handle models starting with a number correctly

* [Rust Server] Additional trace

* [Rust Server] Add support for oneOf/anyOf

* [Rust Server] Update supported features

* [Rust Server] General template tidy up

* [Rust Server] Implement IntoHeaderValue for wrapped data types

* [Rust Server] Convert from string correctly

* [Rust Server] Test for anyOf/oneOf

* Update samples

* Update docs
This commit is contained in:
Richard Whitehouse
2021-01-23 21:32:51 +00:00
committed by GitHub
parent 0068932470
commit 5f2ca61862
28 changed files with 2554 additions and 1492 deletions

View File

@@ -186,7 +186,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
| Name | Supported | Defined By |
| ---- | --------- | ---------- |
|Simple|✓|OAS2,OAS3
|Composite||OAS2,OAS3
|Composite||OAS2,OAS3
|Polymorphism|✗|OAS2,OAS3
|Union|✗|OAS3

View File

@@ -378,38 +378,34 @@ public class InlineModelResolver {
ListIterator<Schema> listIterator = children.listIterator();
while (listIterator.hasNext()) {
Schema component = listIterator.next();
if (component instanceof ObjectSchema || // for inline schema with type:object
(component != null && component.getProperties() != null &&
!component.getProperties().isEmpty())) { // for inline schema without type:object
Schema op = component;
if (op.get$ref() == null && op.getProperties() != null && op.getProperties().size() > 0) {
// If a `title` attribute is defined in the inline schema, codegen uses it to name the
// inline schema. Otherwise, we'll use the default naming such as InlineObject1, etc.
// We know that this is not the best way to name the model.
//
// Such naming strategy may result in issues. If the value of the 'title' attribute
// happens to match a schema defined elsewhere in the specification, 'innerModelName'
// will be the same as that other schema.
//
// To have complete control of the model naming, one can define the model separately
// instead of inline.
String innerModelName = resolveModelName(op.getTitle(), key);
Schema innerModel = modelFromProperty(openAPI, op, innerModelName);
String existing = matchGenerated(innerModel);
if (existing == null) {
openAPI.getComponents().addSchemas(innerModelName, innerModel);
addGenerated(innerModelName, innerModel);
Schema schema = new Schema().$ref(innerModelName);
schema.setRequired(op.getRequired());
listIterator.set(schema);
} else {
Schema schema = new Schema().$ref(existing);
schema.setRequired(op.getRequired());
listIterator.set(schema);
}
if ((component != null) &&
(component.get$ref() == null) &&
((component.getProperties() != null && !component.getProperties().isEmpty()) ||
(component.getEnum() != null && !component.getEnum().isEmpty()))) {
// If a `title` attribute is defined in the inline schema, codegen uses it to name the
// inline schema. Otherwise, we'll use the default naming such as InlineObject1, etc.
// We know that this is not the best way to name the model.
//
// Such naming strategy may result in issues. If the value of the 'title' attribute
// happens to match a schema defined elsewhere in the specification, 'innerModelName'
// will be the same as that other schema.
//
// To have complete control of the model naming, one can define the model separately
// instead of inline.
String innerModelName = resolveModelName(component.getTitle(), key);
Schema innerModel = modelFromProperty(openAPI, component, innerModelName);
String existing = matchGenerated(innerModel);
if (existing == null) {
openAPI.getComponents().addSchemas(innerModelName, innerModel);
addGenerated(innerModelName, innerModel);
Schema schema = new Schema().$ref(innerModelName);
schema.setRequired(component.getRequired());
listIterator.set(schema);
} else {
Schema schema = new Schema().$ref(existing);
schema.setRequired(component.getRequired());
listIterator.set(schema);
}
} else {
// likely a reference to schema (not inline schema)
}
}
}
@@ -540,7 +536,7 @@ public class InlineModelResolver {
*/
private String sanitizeName(final String name) {
return name
.replaceAll("^[0-9]", "_") // e.g. 12object => _2object
.replaceAll("^[0-9]", "_$0") // e.g. 12object => _12object
.replaceAll("[^A-Za-z0-9]", "_"); // e.g. io.schema.User name => io_schema_User_name
}
@@ -671,6 +667,8 @@ public class InlineModelResolver {
model.setXml(xml);
model.setRequired(object.getRequired());
model.setNullable(object.getNullable());
model.setEnum(object.getEnum());
model.setType(object.getType());
model.setDiscriminator(object.getDiscriminator());
model.setWriteOnly(object.getWriteOnly());
model.setUniqueItems(object.getUniqueItems());

View File

@@ -22,6 +22,7 @@ import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.ComposedSchema;
import io.swagger.v3.oas.models.media.FileSchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.XML;
@@ -96,14 +97,11 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
SecurityFeature.OAuth2_Implicit
))
.excludeGlobalFeatures(
GlobalFeature.XMLStructureDefinitions,
GlobalFeature.LinkObjects,
GlobalFeature.ParameterStyling
)
.excludeSchemaSupportFeatures(
SchemaSupportFeature.Polymorphism,
SchemaSupportFeature.Union,
SchemaSupportFeature.Composite
SchemaSupportFeature.Polymorphism
)
.excludeParameterFeatures(
ParameterFeature.Cookie
@@ -400,7 +398,7 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
}
// model name starts with number
else if (name.matches("^\\d.*")) {
else if (camelizedName.matches("^\\d.*")) {
// e.g. 200Response => Model200Response (after camelize)
camelizedName = "Model" + camelizedName;
LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelizedName);
@@ -1191,8 +1189,11 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public CodegenModel fromModel(String name, Schema model) {
LOGGER.trace("Creating model from schema: {}", model);
Map<String, Schema> allDefinitions = ModelUtils.getSchemas(this.openAPI);
CodegenModel mdl = super.fromModel(name, model);
mdl.vendorExtensions.put("x-upper-case-name", name.toUpperCase(Locale.ROOT));
if (!StringUtils.isEmpty(model.get$ref())) {
Schema schema = allDefinitions.get(ModelUtils.getSimpleRef(model.get$ref()));
@@ -1233,6 +1234,8 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
} else {
mdl.arrayModelType = toModelName(mdl.arrayModelType);
}
} else if ((mdl.anyOf.size() > 0) || (mdl.oneOf.size() > 0)) {
mdl.dataType = getSchemaType(model);
}
if (mdl.xmlNamespace != null) {
@@ -1245,6 +1248,8 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
mdl.additionalPropertiesType = getTypeDeclaration(additionalProperties);
}
LOGGER.trace("Created model: {}", mdl);
return mdl;
}
@@ -1403,6 +1408,28 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
return defaultValue;
}
@Override
public String toOneOfName(List<String> names, ComposedSchema composedSchema) {
List<Schema> schemas = ModelUtils.getInterfaces(composedSchema);
List<String> types = new ArrayList<>();
for (Schema s : schemas) {
types.add(getTypeDeclaration(s));
}
return "swagger::OneOf" + types.size() + "<" + String.join(",", types) + ">";
}
@Override
public String toAnyOfName(List<String> names, ComposedSchema composedSchema) {
List<Schema> schemas = ModelUtils.getInterfaces(composedSchema);
List<String> types = new ArrayList<>();
for (Schema s : schemas) {
types.add(getTypeDeclaration(s));
}
return "swagger::AnyOf" + types.size() + "<" + String.join(",", types) + ">";
}
@Override
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
super.postProcessModelProperty(model, property);
@@ -1529,6 +1556,8 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
Map<String, Object> mo = (Map<String, Object>) _mo;
CodegenModel cm = (CodegenModel) mo.get("model");
LOGGER.trace("Post processing model: {}", cm);
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

View File

@@ -4,10 +4,14 @@ use crate::models;
#[cfg(any(feature = "client", feature = "server"))]
use crate::header;
{{! Don't "use" structs here - they can conflict with the names of models, and mean that the code won't compile }}
{{#models}}
{{#model}}
{{#models}}{{#model}}
{{#description}}/// {{{description}}}
{{/description}}{{#isEnum}}/// Enumeration of values.
{{#description}}
/// {{{description}}}
{{/description}}
{{#isEnum}}
/// Enumeration of values.
/// Since this enum's variants do not hold data, we can easily define them them as `#[repr(C)]`
/// which helps with FFI.
#[allow(non_camel_case_types)]
@@ -15,15 +19,23 @@ use crate::header;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "conversion", derive(frunk_enum_derive::LabelledGenericEnum))]{{#xmlName}}
#[serde(rename = "{{{xmlName}}}")]{{/xmlName}}
pub enum {{{classname}}} { {{#allowableValues}}{{#enumVars}}
pub enum {{{classname}}} {
{{#allowableValues}}
{{#enumVars}}
#[serde(rename = {{{value}}})]
{{{name}}},{{/enumVars}}{{/allowableValues}}
{{{name}}},
{{/enumVars}}
{{/allowableValues}}
}
impl std::fmt::Display for {{{classname}}} {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match *self { {{#allowableValues}}{{#enumVars}}
{{{classname}}}::{{{name}}} => write!(f, "{}", {{{value}}}),{{/enumVars}}{{/allowableValues}}
match *self {
{{#allowableValues}}
{{#enumVars}}
{{{classname}}}::{{{name}}} => write!(f, "{}", {{{value}}}),
{{/enumVars}}
{{/allowableValues}}
}
}
}
@@ -62,8 +74,8 @@ impl std::convert::From<{{{dataType}}}> for {{{classname}}} {
{{{classname}}}(x)
}
}
{{#vendorExtensions.x-is-string}}
impl std::string::ToString for {{{classname}}} {
fn to_string(&self) -> String {
self.0.to_string()
@@ -121,45 +133,8 @@ impl ::std::str::FromStr for {{{classname}}} {
{{/additionalPropertiesType}}
{{/dataType}}
{{^dataType}}
// Methods for converting between header::IntoHeaderValue<{{{classname}}}> and hyper::header::HeaderValue
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<header::IntoHeaderValue<{{{classname}}}>> for hyper::header::HeaderValue {
type Error = String;
fn try_from(hdr_value: header::IntoHeaderValue<{{{classname}}}>) -> std::result::Result<Self, Self::Error> {
let hdr_value = hdr_value.to_string();
match hyper::header::HeaderValue::from_str(&hdr_value) {
std::result::Result::Ok(value) => std::result::Result::Ok(value),
std::result::Result::Err(e) => std::result::Result::Err(
format!("Invalid header value for {{classname}} - value: {} is invalid {}",
hdr_value, e))
}
}
}
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<hyper::header::HeaderValue> for header::IntoHeaderValue<{{{classname}}}> {
type Error = String;
fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result<Self, Self::Error> {
match hdr_value.to_str() {
std::result::Result::Ok(value) => {
match <{{{classname}}} as std::str::FromStr>::from_str(value) {
std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)),
std::result::Result::Err(err) => std::result::Result::Err(
format!("Unable to convert header value '{}' into {{classname}} - {}",
value, err))
}
},
std::result::Result::Err(e) => std::result::Result::Err(
format!("Unable to convert header: {:?} to string: {}",
hdr_value, e))
}
}
}
{{#arrayModelType}}{{#vendorExtensions}}{{#x-item-xml-name}}// Utility function for wrapping list elements when serializing xml
{{#arrayModelType}}
{{#vendorExtensions}}{{#x-item-xml-name}}// Utility function for wrapping list elements when serializing xml
#[allow(non_snake_case)]
fn wrap_in_{{{x-item-xml-name}}}<S>(item: &Vec<{{{arrayModelType}}}>, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
@@ -265,7 +240,9 @@ impl std::str::FromStr for {{{classname}}} {
}
}
{{/arrayModelType}}{{^arrayModelType}}{{! general struct}}
{{/arrayModelType}}
{{^arrayModelType}}
{{! general struct}}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))]
{{#xmlName}}
@@ -417,7 +394,7 @@ impl std::str::FromStr for {{{classname}}} {
"{{{baseName}}}" => return std::result::Result::Err("Parsing a nullable type in this style is not supported in {{{classname}}}".to_string()),
{{/isNullable}}
{{^isNullable}}
"{{{baseName}}}" => intermediate_rep.{{{name}}}.push({{{dataType}}}::from_str(val).map_err(|x| format!("{}", x))?),
"{{{baseName}}}" => intermediate_rep.{{{name}}}.push(<{{{dataType}}} as std::str::FromStr>::from_str(val).map_err(|x| format!("{}", x))?),
{{/isNullable}}
{{/isContainer}}
{{/isByteArray}}
@@ -444,22 +421,60 @@ impl std::str::FromStr for {{{classname}}} {
})
}
}
{{/arrayModelType}}
// Methods for converting between header::IntoHeaderValue<{{{classname}}}> and hyper::header::HeaderValue
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<header::IntoHeaderValue<{{{classname}}}>> for hyper::header::HeaderValue {
type Error = String;
fn try_from(hdr_value: header::IntoHeaderValue<{{{classname}}}>) -> std::result::Result<Self, Self::Error> {
let hdr_value = hdr_value.to_string();
match hyper::header::HeaderValue::from_str(&hdr_value) {
std::result::Result::Ok(value) => std::result::Result::Ok(value),
std::result::Result::Err(e) => std::result::Result::Err(
format!("Invalid header value for {{classname}} - value: {} is invalid {}",
hdr_value, e))
}
}
}
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<hyper::header::HeaderValue> for header::IntoHeaderValue<{{{classname}}}> {
type Error = String;
fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result<Self, Self::Error> {
match hdr_value.to_str() {
std::result::Result::Ok(value) => {
match <{{{classname}}} as std::str::FromStr>::from_str(value) {
std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)),
std::result::Result::Err(err) => std::result::Result::Err(
format!("Unable to convert header value '{}' into {{classname}} - {}",
value, err))
}
},
std::result::Result::Err(e) => std::result::Result::Err(
format!("Unable to convert header: {:?} to string: {}",
hdr_value, e))
}
}
}
{{/dataType}}
{{/isEnum}}
{{#usesXml}}
{{#usesXmlNamespaces}}
{{#xmlNamespace}}
impl {{{classname}}} {
/// Associated constant for this model's XML namespace.
#[allow(dead_code)]
pub const NAMESPACE: &'static str = "{{{xmlNamespace}}}";
}
{{/xmlNamespace}}
{{/usesXmlNamespaces}}
impl {{{classname}}} {
/// Helper function to allow us to convert this model to an XML string.
/// Will panic if serialisation fails.
@@ -478,4 +493,4 @@ impl {{{classname}}} {
}
{{/usesXml}}
{{/model}}
{{/models}}
{{/models}}

View File

@@ -42,7 +42,7 @@ pub enum {{{operationId}}}Response {
{{^required}}
Option<
{{/required}}
{{{datatype}}}
{{{dataType}}}
{{^required}}
>
{{/required}}

View File

@@ -357,7 +357,6 @@ paths:
responses:
'200':
description: Success
/repos/{repoId}:
parameters:
- in: path
@@ -391,6 +390,51 @@ paths:
responses:
'200':
description: Success
/one-of:
get:
responses:
'200':
description: Success
content:
application/json:
schema:
oneOf:
- type: integer
- type: array
items:
type: string
/any-of:
get:
parameters:
- name: any-of
in: query
description: list of any of objects
schema:
type: array
items:
$ref: '#/components/schemas/AnyOfObject'
minItems: 1
responses:
'200':
description: Success
content:
application/json:
schema:
$ref: "#/components/schemas/AnyOfObject"
'201':
description: AlternateSuccess
content:
application/json:
schema:
$ref: "#/components/schemas/12345AnyOfObject"
'202':
description: AnyOfSuccess
content:
application/json:
schema:
anyOf:
- $ref: "#/components/schemas/StringObject"
- $ref: "#/components/schemas/UuidObject"
/json-complex-query-param:
get:
parameters:
@@ -418,6 +462,34 @@ components:
test.read: Allowed to read state.
test.write: Allowed to change state.
schemas:
AnyOfProperty:
description: Test containing an anyOf object
properties:
requiredAnyOf:
$ref: '#/components/schemas/AnyOfObject'
optionalAnyOf:
$ref: '#/components/schemas/12345AnyOfObject'
required:
- requiredAnyOf
AnyOfObject:
description: Test a model containing an anyOf
anyOf:
- type: string
enum:
- FOO
- BAR
- type: string
description: Alternate option
12345AnyOfObject:
description: Test a model containing an anyOf that starts with a number
anyOf:
- type: string
enum:
- FOO
- BAR
- "*"
- type: string
description: Alternate option
EnumWithStarObject:
description: Test a model containing a special character in the enum
type: string

View File

@@ -2151,10 +2151,12 @@ components:
properties:
breed:
type: string
type: object
Cat_allOf:
properties:
declawed:
type: boolean
type: object
BigCat_allOf:
properties:
kind:
@@ -2164,6 +2166,7 @@ components:
- leopards
- jaguars
type: string
type: object
securitySchemes:
petstore_auth:
flows:

View File

@@ -1,13 +0,0 @@
# MultipartRequest
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**string_field** | **String** | |
**optional_string_field** | **String** | | [optional] [default to None]
**object_field** | [***models::MultipartRequestObjectField**](multipart_request_object_field.md) | | [optional] [default to None]
**binary_field** | [***swagger::ByteArray**](ByteArray.md) | |
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -4,46 +4,6 @@ use crate::models;
#[cfg(any(feature = "client", feature = "server"))]
use crate::header;
// Methods for converting between header::IntoHeaderValue<InlineObject> and hyper::header::HeaderValue
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<header::IntoHeaderValue<InlineObject>> for hyper::header::HeaderValue {
type Error = String;
fn try_from(hdr_value: header::IntoHeaderValue<InlineObject>) -> std::result::Result<Self, Self::Error> {
let hdr_value = hdr_value.to_string();
match hyper::header::HeaderValue::from_str(&hdr_value) {
std::result::Result::Ok(value) => std::result::Result::Ok(value),
std::result::Result::Err(e) => std::result::Result::Err(
format!("Invalid header value for InlineObject - value: {} is invalid {}",
hdr_value, e))
}
}
}
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<hyper::header::HeaderValue> for header::IntoHeaderValue<InlineObject> {
type Error = String;
fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result<Self, Self::Error> {
match hdr_value.to_str() {
std::result::Result::Ok(value) => {
match <InlineObject as std::str::FromStr>::from_str(value) {
std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)),
std::result::Result::Err(err) => std::result::Result::Err(
format!("Unable to convert header value '{}' into InlineObject - {}",
value, err))
}
},
std::result::Result::Err(e) => std::result::Result::Err(
format!("Unable to convert header: {:?} to string: {}",
hdr_value, e))
}
}
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))]
pub struct InlineObject {
@@ -128,36 +88,34 @@ impl std::str::FromStr for InlineObject {
}
}
// Methods for converting between header::IntoHeaderValue<MultipartRelatedRequest> and hyper::header::HeaderValue
// Methods for converting between header::IntoHeaderValue<InlineObject> and hyper::header::HeaderValue
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<header::IntoHeaderValue<MultipartRelatedRequest>> for hyper::header::HeaderValue {
impl std::convert::TryFrom<header::IntoHeaderValue<InlineObject>> for hyper::header::HeaderValue {
type Error = String;
fn try_from(hdr_value: header::IntoHeaderValue<MultipartRelatedRequest>) -> std::result::Result<Self, Self::Error> {
fn try_from(hdr_value: header::IntoHeaderValue<InlineObject>) -> std::result::Result<Self, Self::Error> {
let hdr_value = hdr_value.to_string();
match hyper::header::HeaderValue::from_str(&hdr_value) {
std::result::Result::Ok(value) => std::result::Result::Ok(value),
std::result::Result::Err(e) => std::result::Result::Err(
format!("Invalid header value for MultipartRelatedRequest - value: {} is invalid {}",
format!("Invalid header value for InlineObject - value: {} is invalid {}",
hdr_value, e))
}
}
}
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<hyper::header::HeaderValue> for header::IntoHeaderValue<MultipartRelatedRequest> {
impl std::convert::TryFrom<hyper::header::HeaderValue> for header::IntoHeaderValue<InlineObject> {
type Error = String;
fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result<Self, Self::Error> {
match hdr_value.to_str() {
std::result::Result::Ok(value) => {
match <MultipartRelatedRequest as std::str::FromStr>::from_str(value) {
match <InlineObject as std::str::FromStr>::from_str(value) {
std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)),
std::result::Result::Err(err) => std::result::Result::Err(
format!("Unable to convert header value '{}' into MultipartRelatedRequest - {}",
format!("Unable to convert header value '{}' into InlineObject - {}",
value, err))
}
},
@@ -242,7 +200,7 @@ impl std::str::FromStr for MultipartRelatedRequest {
if let Some(key) = key_result {
match key {
"object_field" => intermediate_rep.object_field.push(models::MultipartRequestObjectField::from_str(val).map_err(|x| format!("{}", x))?),
"object_field" => intermediate_rep.object_field.push(<models::MultipartRequestObjectField as std::str::FromStr>::from_str(val).map_err(|x| format!("{}", x))?),
"optional_binary_field" => return std::result::Result::Err("Parsing binary data in this style is not supported in MultipartRelatedRequest".to_string()),
"required_binary_field" => return std::result::Result::Err("Parsing binary data in this style is not supported in MultipartRelatedRequest".to_string()),
_ => return std::result::Result::Err("Unexpected key while parsing MultipartRelatedRequest".to_string())
@@ -262,36 +220,34 @@ impl std::str::FromStr for MultipartRelatedRequest {
}
}
// Methods for converting between header::IntoHeaderValue<MultipartRequestObjectField> and hyper::header::HeaderValue
// Methods for converting between header::IntoHeaderValue<MultipartRelatedRequest> and hyper::header::HeaderValue
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<header::IntoHeaderValue<MultipartRequestObjectField>> for hyper::header::HeaderValue {
impl std::convert::TryFrom<header::IntoHeaderValue<MultipartRelatedRequest>> for hyper::header::HeaderValue {
type Error = String;
fn try_from(hdr_value: header::IntoHeaderValue<MultipartRequestObjectField>) -> std::result::Result<Self, Self::Error> {
fn try_from(hdr_value: header::IntoHeaderValue<MultipartRelatedRequest>) -> std::result::Result<Self, Self::Error> {
let hdr_value = hdr_value.to_string();
match hyper::header::HeaderValue::from_str(&hdr_value) {
std::result::Result::Ok(value) => std::result::Result::Ok(value),
std::result::Result::Err(e) => std::result::Result::Err(
format!("Invalid header value for MultipartRequestObjectField - value: {} is invalid {}",
format!("Invalid header value for MultipartRelatedRequest - value: {} is invalid {}",
hdr_value, e))
}
}
}
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<hyper::header::HeaderValue> for header::IntoHeaderValue<MultipartRequestObjectField> {
impl std::convert::TryFrom<hyper::header::HeaderValue> for header::IntoHeaderValue<MultipartRelatedRequest> {
type Error = String;
fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result<Self, Self::Error> {
match hdr_value.to_str() {
std::result::Result::Ok(value) => {
match <MultipartRequestObjectField as std::str::FromStr>::from_str(value) {
match <MultipartRelatedRequest as std::str::FromStr>::from_str(value) {
std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)),
std::result::Result::Err(err) => std::result::Result::Err(
format!("Unable to convert header value '{}' into MultipartRequestObjectField - {}",
format!("Unable to convert header value '{}' into MultipartRelatedRequest - {}",
value, err))
}
},
@@ -372,7 +328,7 @@ impl std::str::FromStr for MultipartRequestObjectField {
if let Some(key) = key_result {
match key {
"field_a" => intermediate_rep.field_a.push(String::from_str(val).map_err(|x| format!("{}", x))?),
"field_a" => intermediate_rep.field_a.push(<String as std::str::FromStr>::from_str(val).map_err(|x| format!("{}", x))?),
"field_b" => return std::result::Result::Err("Parsing a container in this style is not supported in MultipartRequestObjectField".to_string()),
_ => return std::result::Result::Err("Unexpected key while parsing MultipartRequestObjectField".to_string())
}
@@ -390,4 +346,41 @@ impl std::str::FromStr for MultipartRequestObjectField {
}
}
// Methods for converting between header::IntoHeaderValue<MultipartRequestObjectField> and hyper::header::HeaderValue
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<header::IntoHeaderValue<MultipartRequestObjectField>> for hyper::header::HeaderValue {
type Error = String;
fn try_from(hdr_value: header::IntoHeaderValue<MultipartRequestObjectField>) -> std::result::Result<Self, Self::Error> {
let hdr_value = hdr_value.to_string();
match hyper::header::HeaderValue::from_str(&hdr_value) {
std::result::Result::Ok(value) => std::result::Result::Ok(value),
std::result::Result::Err(e) => std::result::Result::Err(
format!("Invalid header value for MultipartRequestObjectField - value: {} is invalid {}",
hdr_value, e))
}
}
}
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<hyper::header::HeaderValue> for header::IntoHeaderValue<MultipartRequestObjectField> {
type Error = String;
fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result<Self, Self::Error> {
match hdr_value.to_str() {
std::result::Result::Ok(value) => {
match <MultipartRequestObjectField as std::str::FromStr>::from_str(value) {
std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)),
std::result::Result::Err(err) => std::result::Result::Err(
format!("Unable to convert header value '{}' into MultipartRequestObjectField - {}",
value, err))
}
},
std::result::Result::Err(e) => std::result::Result::Err(
format!("Unable to convert header: {:?} to string: {}",
hdr_value, e))
}
}
}

View File

@@ -4,46 +4,6 @@ use crate::models;
#[cfg(any(feature = "client", feature = "server"))]
use crate::header;
// Methods for converting between header::IntoHeaderValue<InlineObject> and hyper::header::HeaderValue
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<header::IntoHeaderValue<InlineObject>> for hyper::header::HeaderValue {
type Error = String;
fn try_from(hdr_value: header::IntoHeaderValue<InlineObject>) -> std::result::Result<Self, Self::Error> {
let hdr_value = hdr_value.to_string();
match hyper::header::HeaderValue::from_str(&hdr_value) {
std::result::Result::Ok(value) => std::result::Result::Ok(value),
std::result::Result::Err(e) => std::result::Result::Err(
format!("Invalid header value for InlineObject - value: {} is invalid {}",
hdr_value, e))
}
}
}
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<hyper::header::HeaderValue> for header::IntoHeaderValue<InlineObject> {
type Error = String;
fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result<Self, Self::Error> {
match hdr_value.to_str() {
std::result::Result::Ok(value) => {
match <InlineObject as std::str::FromStr>::from_str(value) {
std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)),
std::result::Result::Err(err) => std::result::Result::Err(
format!("Unable to convert header value '{}' into InlineObject - {}",
value, err))
}
},
std::result::Result::Err(e) => std::result::Result::Err(
format!("Unable to convert header: {:?} to string: {}",
hdr_value, e))
}
}
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))]
pub struct InlineObject {
@@ -104,7 +64,7 @@ impl std::str::FromStr for InlineObject {
if let Some(key) = key_result {
match key {
"propery" => intermediate_rep.propery.push(String::from_str(val).map_err(|x| format!("{}", x))?),
"propery" => intermediate_rep.propery.push(<String as std::str::FromStr>::from_str(val).map_err(|x| format!("{}", x))?),
_ => return std::result::Result::Err("Unexpected key while parsing InlineObject".to_string())
}
}
@@ -120,4 +80,41 @@ impl std::str::FromStr for InlineObject {
}
}
// Methods for converting between header::IntoHeaderValue<InlineObject> and hyper::header::HeaderValue
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<header::IntoHeaderValue<InlineObject>> for hyper::header::HeaderValue {
type Error = String;
fn try_from(hdr_value: header::IntoHeaderValue<InlineObject>) -> std::result::Result<Self, Self::Error> {
let hdr_value = hdr_value.to_string();
match hyper::header::HeaderValue::from_str(&hdr_value) {
std::result::Result::Ok(value) => std::result::Result::Ok(value),
std::result::Result::Err(e) => std::result::Result::Err(
format!("Invalid header value for InlineObject - value: {} is invalid {}",
hdr_value, e))
}
}
}
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<hyper::header::HeaderValue> for header::IntoHeaderValue<InlineObject> {
type Error = String;
fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result<Self, Self::Error> {
match hdr_value.to_str() {
std::result::Result::Ok(value) => {
match <InlineObject as std::str::FromStr>::from_str(value) {
std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)),
std::result::Result::Err(err) => std::result::Result::Err(
format!("Unable to convert header value '{}' into InlineObject - {}",
value, err))
}
},
std::result::Result::Err(e) => std::result::Result::Err(
format!("Unable to convert header: {:?} to string: {}",
hdr_value, e))
}
}
}

View File

@@ -7,11 +7,16 @@ docs/AdditionalPropertiesWithList.md
docs/AnotherXmlArray.md
docs/AnotherXmlInner.md
docs/AnotherXmlObject.md
docs/AnyOfObject.md
docs/AnyOfObjectAnyOf.md
docs/AnyOfProperty.md
docs/DuplicateXmlObject.md
docs/EnumWithStarObject.md
docs/Err.md
docs/Error.md
docs/InlineResponse201.md
docs/Model12345AnyOfObject.md
docs/Model12345AnyOfObjectAnyOf.md
docs/MyId.md
docs/MyIdList.md
docs/NullableTest.md

View File

@@ -61,6 +61,7 @@ cargo run --example server
To run a client, follow one of the following simple steps:
```
cargo run --example client AnyOfGet
cargo run --example client CallbackWithHeaderPost
cargo run --example client ComplexQueryParamGet
cargo run --example client JsonComplexQueryParamGet
@@ -68,6 +69,7 @@ cargo run --example client MandatoryRequestHeaderGet
cargo run --example client MergePatchJsonGet
cargo run --example client MultigetGet
cargo run --example client MultipleAuthSchemeGet
cargo run --example client OneOfGet
cargo run --example client OverrideServerGet
cargo run --example client ParamgetGet
cargo run --example client ReadonlyAuthSchemeGet
@@ -117,6 +119,7 @@ All URIs are relative to *http://localhost*
Method | HTTP request | Description
------------- | ------------- | -------------
[****](docs/default_api.md#) | **GET** /any-of |
[****](docs/default_api.md#) | **POST** /callback-with-header |
[****](docs/default_api.md#) | **GET** /complex-query-param |
[****](docs/default_api.md#) | **GET** /enum_in_path/{path_param} |
@@ -125,6 +128,7 @@ Method | HTTP request | Description
[****](docs/default_api.md#) | **GET** /merge-patch-json |
[****](docs/default_api.md#) | **GET** /multiget | Get some stuff.
[****](docs/default_api.md#) | **GET** /multiple_auth_scheme |
[****](docs/default_api.md#) | **GET** /one-of |
[****](docs/default_api.md#) | **GET** /override-server |
[****](docs/default_api.md#) | **GET** /paramget | Get some stuff with parameters.
[****](docs/default_api.md#) | **GET** /readonly_auth_scheme |
@@ -149,11 +153,16 @@ Method | HTTP request | Description
- [AnotherXmlArray](docs/AnotherXmlArray.md)
- [AnotherXmlInner](docs/AnotherXmlInner.md)
- [AnotherXmlObject](docs/AnotherXmlObject.md)
- [AnyOfObject](docs/AnyOfObject.md)
- [AnyOfObjectAnyOf](docs/AnyOfObjectAnyOf.md)
- [AnyOfProperty](docs/AnyOfProperty.md)
- [DuplicateXmlObject](docs/DuplicateXmlObject.md)
- [EnumWithStarObject](docs/EnumWithStarObject.md)
- [Err](docs/Err.md)
- [Error](docs/Error.md)
- [InlineResponse201](docs/InlineResponse201.md)
- [Model12345AnyOfObject](docs/Model12345AnyOfObject.md)
- [Model12345AnyOfObjectAnyOf](docs/Model12345AnyOfObjectAnyOf.md)
- [MyId](docs/MyId.md)
- [MyIdList](docs/MyIdList.md)
- [NullableTest](docs/NullableTest.md)

View File

@@ -407,6 +407,54 @@ paths:
description: Success
tags:
- Repo
/one-of:
get:
responses:
"200":
content:
application/json:
schema:
oneOf:
- type: integer
- items:
type: string
type: array
description: Success
/any-of:
get:
parameters:
- description: list of any of objects
explode: true
in: query
name: any-of
required: false
schema:
items:
$ref: '#/components/schemas/AnyOfObject'
minItems: 1
type: array
style: form
responses:
"200":
content:
application/json:
schema:
$ref: '#/components/schemas/AnyOfObject'
description: Success
"201":
content:
application/json:
schema:
$ref: '#/components/schemas/12345AnyOfObject'
description: AlternateSuccess
"202":
content:
application/json:
schema:
anyOf:
- $ref: '#/components/schemas/StringObject'
- $ref: '#/components/schemas/UuidObject'
description: AnyOfSuccess
/json-complex-query-param:
get:
parameters:
@@ -426,6 +474,27 @@ paths:
description: Success
components:
schemas:
AnyOfProperty:
description: Test containing an anyOf object
properties:
requiredAnyOf:
$ref: '#/components/schemas/AnyOfObject'
optionalAnyOf:
$ref: '#/components/schemas/12345AnyOfObject'
required:
- requiredAnyOf
AnyOfObject:
anyOf:
- $ref: '#/components/schemas/AnyOfObject_anyOf'
- description: Alternate option
type: string
description: Test a model containing an anyOf
"12345AnyOfObject":
anyOf:
- $ref: '#/components/schemas/_12345AnyOfObject_anyOf'
- description: Alternate option
type: string
description: Test a model containing an anyOf that starts with a number
EnumWithStarObject:
description: Test a model containing a special character in the enum
enum:
@@ -607,6 +676,17 @@ components:
foo:
type: string
type: object
AnyOfObject_anyOf:
enum:
- FOO
- BAR
type: string
_12345AnyOfObject_anyOf:
enum:
- FOO
- BAR
- '*'
type: string
securitySchemes:
authScheme:
flows:

View File

@@ -0,0 +1,9 @@
# AnyOfObject
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -0,0 +1,9 @@
# AnyOfObjectAnyOf
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -0,0 +1,11 @@
# AnyOfProperty
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**required_any_of** | [***models::AnyOfObject**](AnyOfObject.md) | |
**optional_any_of** | [***models::Model12345AnyOfObject**](12345AnyOfObject.md) | | [optional] [default to None]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -0,0 +1,9 @@
# Model12345AnyOfObject
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -0,0 +1,9 @@
# Model12345AnyOfObjectAnyOf
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -4,6 +4,7 @@ All URIs are relative to *http://localhost*
Method | HTTP request | Description
------------- | ------------- | -------------
****](default_api.md#) | **GET** /any-of |
****](default_api.md#) | **POST** /callback-with-header |
****](default_api.md#) | **GET** /complex-query-param |
****](default_api.md#) | **GET** /enum_in_path/{path_param} |
@@ -12,6 +13,7 @@ Method | HTTP request | Description
****](default_api.md#) | **GET** /merge-patch-json |
****](default_api.md#) | **GET** /multiget | Get some stuff.
****](default_api.md#) | **GET** /multiple_auth_scheme |
****](default_api.md#) | **GET** /one-of |
****](default_api.md#) | **GET** /override-server |
****](default_api.md#) | **GET** /paramget | Get some stuff with parameters.
****](default_api.md#) | **GET** /readonly_auth_scheme |
@@ -28,6 +30,38 @@ Method | HTTP request | Description
****](default_api.md#) | **PUT** /xml |
# ****
> models::AnyOfObject (optional)
### Required Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**optional** | **map[string]interface{}** | optional parameters | nil if no parameters
### Optional Parameters
Optional parameters are passed through a map[string]interface{}.
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**any_of** | [**models::AnyOfObject**](models::AnyOfObject.md)| list of any of objects |
### Return type
[**models::AnyOfObject**](AnyOfObject.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# ****
> (url)
@@ -233,6 +267,28 @@ This endpoint does not need any parameter.
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# ****
> swagger::OneOf2<i32,Vec<String>> ()
### Required Parameters
This endpoint does not need any parameter.
### Return type
[**swagger::OneOf2<i32,Vec<String>>**](swagger::OneOf2<i32,Vec<String>>.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# ****
> ()

View File

@@ -6,6 +6,7 @@ mod server;
use futures::{future, Stream, stream};
#[allow(unused_imports)]
use openapi_v3::{Api, ApiNoContext, Client, ContextWrapperExt, models,
AnyOfGetResponse,
CallbackWithHeaderPostResponse,
ComplexQueryParamGetResponse,
EnumInPathPathParamGetResponse,
@@ -14,6 +15,7 @@ use openapi_v3::{Api, ApiNoContext, Client, ContextWrapperExt, models,
MergePatchJsonGetResponse,
MultigetGetResponse,
MultipleAuthSchemeGetResponse,
OneOfGetResponse,
OverrideServerGetResponse,
ParamgetGetResponse,
ReadonlyAuthSchemeGetResponse,
@@ -51,6 +53,7 @@ fn main() {
.arg(Arg::with_name("operation")
.help("Sets the operation to run")
.possible_values(&[
"AnyOfGet",
"CallbackWithHeaderPost",
"ComplexQueryParamGet",
"JsonComplexQueryParamGet",
@@ -58,6 +61,7 @@ fn main() {
"MergePatchJsonGet",
"MultigetGet",
"MultipleAuthSchemeGet",
"OneOfGet",
"OverrideServerGet",
"ParamgetGet",
"ReadonlyAuthSchemeGet",
@@ -120,6 +124,12 @@ fn main() {
rt.spawn(server::create("127.0.0.1:8081", false));
match matches.value_of("operation") {
Some("AnyOfGet") => {
let result = rt.block_on(client.any_of_get(
Some(&Vec::new())
));
info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has<XSpanIdString>).get().clone());
},
Some("CallbackWithHeaderPost") => {
let result = rt.block_on(client.callback_with_header_post(
"url_example".to_string()
@@ -167,6 +177,11 @@ fn main() {
));
info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has<XSpanIdString>).get().clone());
},
Some("OneOfGet") => {
let result = rt.block_on(client.one_of_get(
));
info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has<XSpanIdString>).get().clone());
},
Some("OverrideServerGet") => {
let result = rt.block_on(client.override_server_get(
));

View File

@@ -96,6 +96,7 @@ impl<C> Server<C> {
use openapi_v3::{
Api,
AnyOfGetResponse,
CallbackWithHeaderPostResponse,
ComplexQueryParamGetResponse,
EnumInPathPathParamGetResponse,
@@ -104,6 +105,7 @@ use openapi_v3::{
MergePatchJsonGetResponse,
MultigetGetResponse,
MultipleAuthSchemeGetResponse,
OneOfGetResponse,
OverrideServerGetResponse,
ParamgetGetResponse,
ReadonlyAuthSchemeGetResponse,
@@ -128,6 +130,16 @@ use swagger::ApiError;
#[async_trait]
impl<C> Api<C> for Server<C> where C: Has<XSpanIdString> + Send + Sync
{
async fn any_of_get(
&self,
any_of: Option<&Vec<models::AnyOfObject>>,
context: &C) -> Result<AnyOfGetResponse, ApiError>
{
let context = context.clone();
info!("any_of_get({:?}) - X-Span-ID: {:?}", any_of, context.get().0.clone());
Err("Generic failuare".into())
}
async fn callback_with_header_post(
&self,
url: String,
@@ -206,6 +218,15 @@ impl<C> Api<C> for Server<C> where C: Has<XSpanIdString> + Send + Sync
Err("Generic failuare".into())
}
async fn one_of_get(
&self,
context: &C) -> Result<OneOfGetResponse, ApiError>
{
let context = context.clone();
info!("one_of_get() - X-Span-ID: {:?}", context.get().0.clone());
Err("Generic failuare".into())
}
async fn override_server_get(
&self,
context: &C) -> Result<OverrideServerGetResponse, ApiError>

View File

@@ -36,6 +36,7 @@ const FRAGMENT_ENCODE_SET: &AsciiSet = &percent_encoding::CONTROLS
const ID_ENCODE_SET: &AsciiSet = &FRAGMENT_ENCODE_SET.add(b'|');
use crate::{Api,
AnyOfGetResponse,
CallbackWithHeaderPostResponse,
ComplexQueryParamGetResponse,
EnumInPathPathParamGetResponse,
@@ -44,6 +45,7 @@ use crate::{Api,
MergePatchJsonGetResponse,
MultigetGetResponse,
MultipleAuthSchemeGetResponse,
OneOfGetResponse,
OverrideServerGetResponse,
ParamgetGetResponse,
ReadonlyAuthSchemeGetResponse,
@@ -405,6 +407,110 @@ impl<S, C> Api<C> for Client<S, C> where
}
}
async fn any_of_get(
&self,
param_any_of: Option<&Vec<models::AnyOfObject>>,
context: &C) -> Result<AnyOfGetResponse, ApiError>
{
let mut client_service = self.client_service.clone();
let mut uri = format!(
"{}/any-of",
self.base_path
);
// Query parameters
let query_string = {
let mut query_string = form_urlencoded::Serializer::new("".to_owned());
if let Some(param_any_of) = param_any_of {
query_string.append_pair("any-of",
&param_any_of.iter().map(ToString::to_string).collect::<Vec<String>>().join(","));
}
query_string.finish()
};
if !query_string.is_empty() {
uri += "?";
uri += &query_string;
}
let uri = match Uri::from_str(&uri) {
Ok(uri) => uri,
Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))),
};
let mut request = match Request::builder()
.method("GET")
.uri(uri)
.body(Body::empty()) {
Ok(req) => req,
Err(e) => return Err(ApiError(format!("Unable to create request: {}", e)))
};
let header = HeaderValue::from_str(Has::<XSpanIdString>::get(context).0.clone().to_string().as_str());
request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header {
Ok(h) => h,
Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e)))
});
let mut response = client_service.call((request, context.clone()))
.map_err(|e| ApiError(format!("No response received: {}", e))).await?;
match response.status().as_u16() {
200 => {
let body = response.into_body();
let body = body
.to_raw()
.map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?;
let body = str::from_utf8(&body)
.map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?;
let body = serde_json::from_str::<models::AnyOfObject>(body)?;
Ok(AnyOfGetResponse::Success
(body)
)
}
201 => {
let body = response.into_body();
let body = body
.to_raw()
.map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?;
let body = str::from_utf8(&body)
.map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?;
let body = serde_json::from_str::<models::Model12345AnyOfObject>(body)?;
Ok(AnyOfGetResponse::AlternateSuccess
(body)
)
}
202 => {
let body = response.into_body();
let body = body
.to_raw()
.map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?;
let body = str::from_utf8(&body)
.map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?;
let body = serde_json::from_str::<swagger::AnyOf2<models::StringObject,models::UuidObject>>(body)?;
Ok(AnyOfGetResponse::AnyOfSuccess
(body)
)
}
code => {
let headers = response.headers().clone();
let body = response.into_body()
.take(100)
.to_raw().await;
Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}",
code,
headers,
match body {
Ok(body) => match String::from_utf8(body) {
Ok(body) => body,
Err(e) => format!("<Body was not UTF8: {:?}>", e),
},
Err(e) => format!("<Failed to read body: {}>", e),
}
)))
}
}
}
async fn callback_with_header_post(
&self,
param_url: String,
@@ -1089,6 +1195,81 @@ impl<S, C> Api<C> for Client<S, C> where
}
}
async fn one_of_get(
&self,
context: &C) -> Result<OneOfGetResponse, ApiError>
{
let mut client_service = self.client_service.clone();
let mut uri = format!(
"{}/one-of",
self.base_path
);
// Query parameters
let query_string = {
let mut query_string = form_urlencoded::Serializer::new("".to_owned());
query_string.finish()
};
if !query_string.is_empty() {
uri += "?";
uri += &query_string;
}
let uri = match Uri::from_str(&uri) {
Ok(uri) => uri,
Err(err) => return Err(ApiError(format!("Unable to build URI: {}", err))),
};
let mut request = match Request::builder()
.method("GET")
.uri(uri)
.body(Body::empty()) {
Ok(req) => req,
Err(e) => return Err(ApiError(format!("Unable to create request: {}", e)))
};
let header = HeaderValue::from_str(Has::<XSpanIdString>::get(context).0.clone().to_string().as_str());
request.headers_mut().insert(HeaderName::from_static("x-span-id"), match header {
Ok(h) => h,
Err(e) => return Err(ApiError(format!("Unable to create X-Span ID header value: {}", e)))
});
let mut response = client_service.call((request, context.clone()))
.map_err(|e| ApiError(format!("No response received: {}", e))).await?;
match response.status().as_u16() {
200 => {
let body = response.into_body();
let body = body
.to_raw()
.map_err(|e| ApiError(format!("Failed to read response: {}", e))).await?;
let body = str::from_utf8(&body)
.map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e)))?;
let body = serde_json::from_str::<swagger::OneOf2<i32,Vec<String>>>(body)?;
Ok(OneOfGetResponse::Success
(body)
)
}
code => {
let headers = response.headers().clone();
let body = response.into_body()
.take(100)
.to_raw().await;
Err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}",
code,
headers,
match body {
Ok(body) => match String::from_utf8(body) {
Ok(body) => body,
Err(e) => format!("<Body was not UTF8: {:?}>", e),
},
Err(e) => format!("<Failed to read body: {}>", e),
}
)))
}
}
}
async fn override_server_get(
&self,
context: &C) -> Result<OverrideServerGetResponse, ApiError>

View File

@@ -11,6 +11,22 @@ type ServiceError = Box<dyn Error + Send + Sync + 'static>;
pub const BASE_PATH: &'static str = "";
pub const API_VERSION: &'static str = "1.0.7";
#[derive(Debug, PartialEq)]
#[must_use]
pub enum AnyOfGetResponse {
/// Success
Success
(models::AnyOfObject)
,
/// AlternateSuccess
AlternateSuccess
(models::Model12345AnyOfObject)
,
/// AnyOfSuccess
AnyOfSuccess
(swagger::AnyOf2<models::StringObject,models::UuidObject>)
}
#[derive(Debug, PartialEq)]
pub enum CallbackWithHeaderPostResponse {
/// OK
@@ -86,6 +102,13 @@ pub enum MultipleAuthSchemeGetResponse {
CheckThatLimitingToMultipleRequiredAuthSchemesWorks
}
#[derive(Debug, PartialEq)]
pub enum OneOfGetResponse {
/// Success
Success
(swagger::OneOf2<i32,Vec<String>>)
}
#[derive(Debug, PartialEq)]
pub enum OverrideServerGetResponse {
/// Success.
@@ -253,6 +276,11 @@ pub trait Api<C: Send + Sync> {
Poll::Ready(Ok(()))
}
async fn any_of_get(
&self,
any_of: Option<&Vec<models::AnyOfObject>>,
context: &C) -> Result<AnyOfGetResponse, ApiError>;
async fn callback_with_header_post(
&self,
url: String,
@@ -291,6 +319,10 @@ pub trait Api<C: Send + Sync> {
&self,
context: &C) -> Result<MultipleAuthSchemeGetResponse, ApiError>;
async fn one_of_get(
&self,
context: &C) -> Result<OneOfGetResponse, ApiError>;
async fn override_server_get(
&self,
context: &C) -> Result<OverrideServerGetResponse, ApiError>;
@@ -380,6 +412,11 @@ pub trait ApiNoContext<C: Send + Sync> {
fn context(&self) -> &C;
async fn any_of_get(
&self,
any_of: Option<&Vec<models::AnyOfObject>>,
) -> Result<AnyOfGetResponse, ApiError>;
async fn callback_with_header_post(
&self,
url: String,
@@ -418,6 +455,10 @@ pub trait ApiNoContext<C: Send + Sync> {
&self,
) -> Result<MultipleAuthSchemeGetResponse, ApiError>;
async fn one_of_get(
&self,
) -> Result<OneOfGetResponse, ApiError>;
async fn override_server_get(
&self,
) -> Result<OverrideServerGetResponse, ApiError>;
@@ -522,6 +563,15 @@ impl<T: Api<C> + Send + Sync, C: Clone + Send + Sync> ApiNoContext<C> for Contex
ContextWrapper::context(self)
}
async fn any_of_get(
&self,
any_of: Option<&Vec<models::AnyOfObject>>,
) -> Result<AnyOfGetResponse, ApiError>
{
let context = self.context().clone();
self.api().any_of_get(any_of, &context).await
}
async fn callback_with_header_post(
&self,
url: String,
@@ -592,6 +642,14 @@ impl<T: Api<C> + Send + Sync, C: Clone + Send + Sync> ApiNoContext<C> for Contex
self.api().multiple_auth_scheme_get(&context).await
}
async fn one_of_get(
&self,
) -> Result<OneOfGetResponse, ApiError>
{
let context = self.context().clone();
self.api().one_of_get(&context).await
}
async fn override_server_get(
&self,
) -> Result<OverrideServerGetResponse, ApiError>

View File

@@ -22,6 +22,7 @@ pub use crate::context;
type ServiceFuture = BoxFuture<'static, Result<Response<Body>, crate::ServiceError>>;
use crate::{Api,
AnyOfGetResponse,
CallbackWithHeaderPostResponse,
ComplexQueryParamGetResponse,
EnumInPathPathParamGetResponse,
@@ -30,6 +31,7 @@ use crate::{Api,
MergePatchJsonGetResponse,
MultigetGetResponse,
MultipleAuthSchemeGetResponse,
OneOfGetResponse,
OverrideServerGetResponse,
ParamgetGetResponse,
ReadonlyAuthSchemeGetResponse,
@@ -55,6 +57,7 @@ mod paths {
lazy_static! {
pub static ref GLOBAL_REGEX_SET: regex::RegexSet = regex::RegexSet::new(vec![
r"^/any-of$",
r"^/callback-with-header$",
r"^/complex-query-param$",
r"^/enum_in_path/(?P<path_param>[^/?#]*)$",
@@ -63,6 +66,7 @@ mod paths {
r"^/merge-patch-json$",
r"^/multiget$",
r"^/multiple_auth_scheme$",
r"^/one-of$",
r"^/override-server$",
r"^/paramget$",
r"^/readonly_auth_scheme$",
@@ -80,38 +84,40 @@ mod paths {
])
.expect("Unable to create global regex set");
}
pub(crate) static ID_CALLBACK_WITH_HEADER: usize = 0;
pub(crate) static ID_COMPLEX_QUERY_PARAM: usize = 1;
pub(crate) static ID_ENUM_IN_PATH_PATH_PARAM: usize = 2;
pub(crate) static ID_ANY_OF: usize = 0;
pub(crate) static ID_CALLBACK_WITH_HEADER: usize = 1;
pub(crate) static ID_COMPLEX_QUERY_PARAM: usize = 2;
pub(crate) static ID_ENUM_IN_PATH_PATH_PARAM: usize = 3;
lazy_static! {
pub static ref REGEX_ENUM_IN_PATH_PATH_PARAM: regex::Regex =
regex::Regex::new(r"^/enum_in_path/(?P<path_param>[^/?#]*)$")
.expect("Unable to create regex for ENUM_IN_PATH_PATH_PARAM");
}
pub(crate) static ID_JSON_COMPLEX_QUERY_PARAM: usize = 3;
pub(crate) static ID_MANDATORY_REQUEST_HEADER: usize = 4;
pub(crate) static ID_MERGE_PATCH_JSON: usize = 5;
pub(crate) static ID_MULTIGET: usize = 6;
pub(crate) static ID_MULTIPLE_AUTH_SCHEME: usize = 7;
pub(crate) static ID_OVERRIDE_SERVER: usize = 8;
pub(crate) static ID_PARAMGET: usize = 9;
pub(crate) static ID_READONLY_AUTH_SCHEME: usize = 10;
pub(crate) static ID_REGISTER_CALLBACK: usize = 11;
pub(crate) static ID_REPOS: usize = 12;
pub(crate) static ID_REPOS_REPOID: usize = 13;
pub(crate) static ID_JSON_COMPLEX_QUERY_PARAM: usize = 4;
pub(crate) static ID_MANDATORY_REQUEST_HEADER: usize = 5;
pub(crate) static ID_MERGE_PATCH_JSON: usize = 6;
pub(crate) static ID_MULTIGET: usize = 7;
pub(crate) static ID_MULTIPLE_AUTH_SCHEME: usize = 8;
pub(crate) static ID_ONE_OF: usize = 9;
pub(crate) static ID_OVERRIDE_SERVER: usize = 10;
pub(crate) static ID_PARAMGET: usize = 11;
pub(crate) static ID_READONLY_AUTH_SCHEME: usize = 12;
pub(crate) static ID_REGISTER_CALLBACK: usize = 13;
pub(crate) static ID_REPOS: usize = 14;
pub(crate) static ID_REPOS_REPOID: usize = 15;
lazy_static! {
pub static ref REGEX_REPOS_REPOID: regex::Regex =
regex::Regex::new(r"^/repos/(?P<repoId>[^/?#]*)$")
.expect("Unable to create regex for REPOS_REPOID");
}
pub(crate) static ID_REQUIRED_OCTET_STREAM: usize = 14;
pub(crate) static ID_RESPONSES_WITH_HEADERS: usize = 15;
pub(crate) static ID_RFC7807: usize = 16;
pub(crate) static ID_UNTYPED_PROPERTY: usize = 17;
pub(crate) static ID_UUID: usize = 18;
pub(crate) static ID_XML: usize = 19;
pub(crate) static ID_XML_EXTRA: usize = 20;
pub(crate) static ID_XML_OTHER: usize = 21;
pub(crate) static ID_REQUIRED_OCTET_STREAM: usize = 16;
pub(crate) static ID_RESPONSES_WITH_HEADERS: usize = 17;
pub(crate) static ID_RFC7807: usize = 18;
pub(crate) static ID_UNTYPED_PROPERTY: usize = 19;
pub(crate) static ID_UUID: usize = 20;
pub(crate) static ID_XML: usize = 21;
pub(crate) static ID_XML_EXTRA: usize = 22;
pub(crate) static ID_XML_OTHER: usize = 23;
}
pub struct MakeService<T, C> where
@@ -216,6 +222,76 @@ impl<T, C> hyper::service::Service<(Request<Body>, C)> for Service<T, C> where
match &method {
// AnyOfGet - GET /any-of
&hyper::Method::GET if path.matched(paths::ID_ANY_OF) => {
// Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response)
let query_params = form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()).collect::<Vec<_>>();
let param_any_of = query_params.iter().filter(|e| e.0 == "any-of").map(|e| e.1.to_owned())
.filter_map(|param_any_of| param_any_of.parse().ok())
.collect::<Vec<_>>();
let param_any_of = if !param_any_of.is_empty() {
Some(param_any_of)
} else {
None
};
let result = api_impl.any_of_get(
param_any_of.as_ref(),
&context
).await;
let mut response = Response::new(Body::empty());
response.headers_mut().insert(
HeaderName::from_static("x-span-id"),
HeaderValue::from_str((&context as &dyn Has<XSpanIdString>).get().0.clone().to_string().as_str())
.expect("Unable to create X-Span-ID header value"));
match result {
Ok(rsp) => match rsp {
AnyOfGetResponse::Success
(body)
=> {
*response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode");
response.headers_mut().insert(
CONTENT_TYPE,
HeaderValue::from_str("application/json")
.expect("Unable to create Content-Type header for ANY_OF_GET_SUCCESS"));
let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
*response.body_mut() = Body::from(body);
},
AnyOfGetResponse::AlternateSuccess
(body)
=> {
*response.status_mut() = StatusCode::from_u16(201).expect("Unable to turn 201 into a StatusCode");
response.headers_mut().insert(
CONTENT_TYPE,
HeaderValue::from_str("application/json")
.expect("Unable to create Content-Type header for ANY_OF_GET_ALTERNATE_SUCCESS"));
let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
*response.body_mut() = Body::from(body);
},
AnyOfGetResponse::AnyOfSuccess
(body)
=> {
*response.status_mut() = StatusCode::from_u16(202).expect("Unable to turn 202 into a StatusCode");
response.headers_mut().insert(
CONTENT_TYPE,
HeaderValue::from_str("application/json")
.expect("Unable to create Content-Type header for ANY_OF_GET_ANY_OF_SUCCESS"));
let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
*response.body_mut() = Body::from(body);
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
*response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
*response.body_mut() = Body::from("An internal error occurred");
},
}
Ok(response)
},
// CallbackWithHeaderPost - POST /callback-with-header
&hyper::Method::POST if path.matched(paths::ID_CALLBACK_WITH_HEADER) => {
// Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response)
@@ -667,6 +743,42 @@ impl<T, C> hyper::service::Service<(Request<Body>, C)> for Service<T, C> where
Ok(response)
},
// OneOfGet - GET /one-of
&hyper::Method::GET if path.matched(paths::ID_ONE_OF) => {
let result = api_impl.one_of_get(
&context
).await;
let mut response = Response::new(Body::empty());
response.headers_mut().insert(
HeaderName::from_static("x-span-id"),
HeaderValue::from_str((&context as &dyn Has<XSpanIdString>).get().0.clone().to_string().as_str())
.expect("Unable to create X-Span-ID header value"));
match result {
Ok(rsp) => match rsp {
OneOfGetResponse::Success
(body)
=> {
*response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode");
response.headers_mut().insert(
CONTENT_TYPE,
HeaderValue::from_str("application/json")
.expect("Unable to create Content-Type header for ONE_OF_GET_SUCCESS"));
let body = serde_json::to_string(&body).expect("impossible to fail to serialize");
*response.body_mut() = Body::from(body);
},
},
Err(_) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
*response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
*response.body_mut() = Body::from("An internal error occurred");
},
}
Ok(response)
},
// OverrideServerGet - GET /override-server
&hyper::Method::GET if path.matched(paths::ID_OVERRIDE_SERVER) => {
let result = api_impl.override_server_get(
@@ -1722,6 +1834,7 @@ impl<T, C> hyper::service::Service<(Request<Body>, C)> for Service<T, C> where
Ok(response)
},
_ if path.matched(paths::ID_ANY_OF) => method_not_allowed(),
_ if path.matched(paths::ID_CALLBACK_WITH_HEADER) => method_not_allowed(),
_ if path.matched(paths::ID_COMPLEX_QUERY_PARAM) => method_not_allowed(),
_ if path.matched(paths::ID_ENUM_IN_PATH_PATH_PARAM) => method_not_allowed(),
@@ -1730,6 +1843,7 @@ impl<T, C> hyper::service::Service<(Request<Body>, C)> for Service<T, C> where
_ if path.matched(paths::ID_MERGE_PATCH_JSON) => method_not_allowed(),
_ if path.matched(paths::ID_MULTIGET) => method_not_allowed(),
_ if path.matched(paths::ID_MULTIPLE_AUTH_SCHEME) => method_not_allowed(),
_ if path.matched(paths::ID_ONE_OF) => method_not_allowed(),
_ if path.matched(paths::ID_OVERRIDE_SERVER) => method_not_allowed(),
_ if path.matched(paths::ID_PARAMGET) => method_not_allowed(),
_ if path.matched(paths::ID_READONLY_AUTH_SCHEME) => method_not_allowed(),
@@ -1757,6 +1871,8 @@ impl<T> RequestParser<T> for ApiRequestParser {
fn parse_operation_id(request: &Request<T>) -> Result<&'static str, ()> {
let path = paths::GLOBAL_REGEX_SET.matches(request.uri().path());
match request.method() {
// AnyOfGet - GET /any-of
&hyper::Method::GET if path.matched(paths::ID_ANY_OF) => Ok("AnyOfGet"),
// CallbackWithHeaderPost - POST /callback-with-header
&hyper::Method::POST if path.matched(paths::ID_CALLBACK_WITH_HEADER) => Ok("CallbackWithHeaderPost"),
// ComplexQueryParamGet - GET /complex-query-param
@@ -1773,6 +1889,8 @@ impl<T> RequestParser<T> for ApiRequestParser {
&hyper::Method::GET if path.matched(paths::ID_MULTIGET) => Ok("MultigetGet"),
// MultipleAuthSchemeGet - GET /multiple_auth_scheme
&hyper::Method::GET if path.matched(paths::ID_MULTIPLE_AUTH_SCHEME) => Ok("MultipleAuthSchemeGet"),
// OneOfGet - GET /one-of
&hyper::Method::GET if path.matched(paths::ID_ONE_OF) => Ok("OneOfGet"),
// OverrideServerGet - GET /override-server
&hyper::Method::GET if path.matched(paths::ID_OVERRIDE_SERVER) => Ok("OverrideServerGet"),
// ParamgetGet - GET /paramget

View File

@@ -3,4 +3,3 @@
use crate::models;
#[cfg(any(feature = "client", feature = "server"))]
use crate::header;

View File

@@ -4,46 +4,6 @@ use crate::models;
#[cfg(any(feature = "client", feature = "server"))]
use crate::header;
// Methods for converting between header::IntoHeaderValue<ANullableContainer> and hyper::header::HeaderValue
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<header::IntoHeaderValue<ANullableContainer>> for hyper::header::HeaderValue {
type Error = String;
fn try_from(hdr_value: header::IntoHeaderValue<ANullableContainer>) -> std::result::Result<Self, Self::Error> {
let hdr_value = hdr_value.to_string();
match hyper::header::HeaderValue::from_str(&hdr_value) {
std::result::Result::Ok(value) => std::result::Result::Ok(value),
std::result::Result::Err(e) => std::result::Result::Err(
format!("Invalid header value for ANullableContainer - value: {} is invalid {}",
hdr_value, e))
}
}
}
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<hyper::header::HeaderValue> for header::IntoHeaderValue<ANullableContainer> {
type Error = String;
fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result<Self, Self::Error> {
match hdr_value.to_str() {
std::result::Result::Ok(value) => {
match <ANullableContainer as std::str::FromStr>::from_str(value) {
std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)),
std::result::Result::Err(err) => std::result::Result::Err(
format!("Unable to convert header value '{}' into ANullableContainer - {}",
value, err))
}
},
std::result::Result::Err(e) => std::result::Result::Err(
format!("Unable to convert header: {:?} to string: {}",
hdr_value, e))
}
}
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))]
pub struct ANullableContainer {
@@ -133,6 +93,43 @@ impl std::str::FromStr for ANullableContainer {
}
}
// Methods for converting between header::IntoHeaderValue<ANullableContainer> and hyper::header::HeaderValue
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<header::IntoHeaderValue<ANullableContainer>> for hyper::header::HeaderValue {
type Error = String;
fn try_from(hdr_value: header::IntoHeaderValue<ANullableContainer>) -> std::result::Result<Self, Self::Error> {
let hdr_value = hdr_value.to_string();
match hyper::header::HeaderValue::from_str(&hdr_value) {
std::result::Result::Ok(value) => std::result::Result::Ok(value),
std::result::Result::Err(e) => std::result::Result::Err(
format!("Invalid header value for ANullableContainer - value: {} is invalid {}",
hdr_value, e))
}
}
}
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<hyper::header::HeaderValue> for header::IntoHeaderValue<ANullableContainer> {
type Error = String;
fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result<Self, Self::Error> {
match hdr_value.to_str() {
std::result::Result::Ok(value) => {
match <ANullableContainer as std::str::FromStr>::from_str(value) {
std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)),
std::result::Result::Err(err) => std::result::Result::Err(
format!("Unable to convert header value '{}' into ANullableContainer - {}",
value, err))
}
},
std::result::Result::Err(e) => std::result::Result::Err(
format!("Unable to convert header: {:?} to string: {}",
hdr_value, e))
}
}
}
/// An additionalPropertiesObject
@@ -146,7 +143,6 @@ impl std::convert::From<std::collections::HashMap<String, String>> for Additiona
}
}
impl std::convert::From<AdditionalPropertiesObject> for std::collections::HashMap<String, String> {
fn from(x: AdditionalPropertiesObject) -> Self {
x.0
@@ -187,46 +183,6 @@ impl ::std::str::FromStr for AdditionalPropertiesObject {
}
}
// Methods for converting between header::IntoHeaderValue<AllOfObject> and hyper::header::HeaderValue
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<header::IntoHeaderValue<AllOfObject>> for hyper::header::HeaderValue {
type Error = String;
fn try_from(hdr_value: header::IntoHeaderValue<AllOfObject>) -> std::result::Result<Self, Self::Error> {
let hdr_value = hdr_value.to_string();
match hyper::header::HeaderValue::from_str(&hdr_value) {
std::result::Result::Ok(value) => std::result::Result::Ok(value),
std::result::Result::Err(e) => std::result::Result::Err(
format!("Invalid header value for AllOfObject - value: {} is invalid {}",
hdr_value, e))
}
}
}
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<hyper::header::HeaderValue> for header::IntoHeaderValue<AllOfObject> {
type Error = String;
fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result<Self, Self::Error> {
match hdr_value.to_str() {
std::result::Result::Ok(value) => {
match <AllOfObject as std::str::FromStr>::from_str(value) {
std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)),
std::result::Result::Err(err) => std::result::Result::Err(
format!("Unable to convert header value '{}' into AllOfObject - {}",
value, err))
}
},
std::result::Result::Err(e) => std::result::Result::Err(
format!("Unable to convert header: {:?} to string: {}",
hdr_value, e))
}
}
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))]
pub struct AllOfObject {
@@ -299,8 +255,8 @@ impl std::str::FromStr for AllOfObject {
if let Some(key) = key_result {
match key {
"sampleProperty" => intermediate_rep.sample_property.push(String::from_str(val).map_err(|x| format!("{}", x))?),
"sampleBasePropery" => intermediate_rep.sample_base_propery.push(String::from_str(val).map_err(|x| format!("{}", x))?),
"sampleProperty" => intermediate_rep.sample_property.push(<String as std::str::FromStr>::from_str(val).map_err(|x| format!("{}", x))?),
"sampleBasePropery" => intermediate_rep.sample_base_propery.push(<String as std::str::FromStr>::from_str(val).map_err(|x| format!("{}", x))?),
_ => return std::result::Result::Err("Unexpected key while parsing AllOfObject".to_string())
}
}
@@ -317,36 +273,34 @@ impl std::str::FromStr for AllOfObject {
}
}
// Methods for converting between header::IntoHeaderValue<BaseAllOf> and hyper::header::HeaderValue
// Methods for converting between header::IntoHeaderValue<AllOfObject> and hyper::header::HeaderValue
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<header::IntoHeaderValue<BaseAllOf>> for hyper::header::HeaderValue {
impl std::convert::TryFrom<header::IntoHeaderValue<AllOfObject>> for hyper::header::HeaderValue {
type Error = String;
fn try_from(hdr_value: header::IntoHeaderValue<BaseAllOf>) -> std::result::Result<Self, Self::Error> {
fn try_from(hdr_value: header::IntoHeaderValue<AllOfObject>) -> std::result::Result<Self, Self::Error> {
let hdr_value = hdr_value.to_string();
match hyper::header::HeaderValue::from_str(&hdr_value) {
std::result::Result::Ok(value) => std::result::Result::Ok(value),
std::result::Result::Err(e) => std::result::Result::Err(
format!("Invalid header value for BaseAllOf - value: {} is invalid {}",
format!("Invalid header value for AllOfObject - value: {} is invalid {}",
hdr_value, e))
}
}
}
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<hyper::header::HeaderValue> for header::IntoHeaderValue<BaseAllOf> {
impl std::convert::TryFrom<hyper::header::HeaderValue> for header::IntoHeaderValue<AllOfObject> {
type Error = String;
fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result<Self, Self::Error> {
match hdr_value.to_str() {
std::result::Result::Ok(value) => {
match <BaseAllOf as std::str::FromStr>::from_str(value) {
match <AllOfObject as std::str::FromStr>::from_str(value) {
std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)),
std::result::Result::Err(err) => std::result::Result::Err(
format!("Unable to convert header value '{}' into BaseAllOf - {}",
format!("Unable to convert header value '{}' into AllOfObject - {}",
value, err))
}
},
@@ -418,7 +372,7 @@ impl std::str::FromStr for BaseAllOf {
if let Some(key) = key_result {
match key {
"sampleBasePropery" => intermediate_rep.sample_base_propery.push(String::from_str(val).map_err(|x| format!("{}", x))?),
"sampleBasePropery" => intermediate_rep.sample_base_propery.push(<String as std::str::FromStr>::from_str(val).map_err(|x| format!("{}", x))?),
_ => return std::result::Result::Err("Unexpected key while parsing BaseAllOf".to_string())
}
}
@@ -434,37 +388,34 @@ impl std::str::FromStr for BaseAllOf {
}
}
/// structured response
// Methods for converting between header::IntoHeaderValue<GetYamlResponse> and hyper::header::HeaderValue
// Methods for converting between header::IntoHeaderValue<BaseAllOf> and hyper::header::HeaderValue
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<header::IntoHeaderValue<GetYamlResponse>> for hyper::header::HeaderValue {
impl std::convert::TryFrom<header::IntoHeaderValue<BaseAllOf>> for hyper::header::HeaderValue {
type Error = String;
fn try_from(hdr_value: header::IntoHeaderValue<GetYamlResponse>) -> std::result::Result<Self, Self::Error> {
fn try_from(hdr_value: header::IntoHeaderValue<BaseAllOf>) -> std::result::Result<Self, Self::Error> {
let hdr_value = hdr_value.to_string();
match hyper::header::HeaderValue::from_str(&hdr_value) {
std::result::Result::Ok(value) => std::result::Result::Ok(value),
std::result::Result::Err(e) => std::result::Result::Err(
format!("Invalid header value for GetYamlResponse - value: {} is invalid {}",
format!("Invalid header value for BaseAllOf - value: {} is invalid {}",
hdr_value, e))
}
}
}
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<hyper::header::HeaderValue> for header::IntoHeaderValue<GetYamlResponse> {
impl std::convert::TryFrom<hyper::header::HeaderValue> for header::IntoHeaderValue<BaseAllOf> {
type Error = String;
fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result<Self, Self::Error> {
match hdr_value.to_str() {
std::result::Result::Ok(value) => {
match <GetYamlResponse as std::str::FromStr>::from_str(value) {
match <BaseAllOf as std::str::FromStr>::from_str(value) {
std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)),
std::result::Result::Err(err) => std::result::Result::Err(
format!("Unable to convert header value '{}' into GetYamlResponse - {}",
format!("Unable to convert header value '{}' into BaseAllOf - {}",
value, err))
}
},
@@ -476,6 +427,7 @@ impl std::convert::TryFrom<hyper::header::HeaderValue> for header::IntoHeaderVal
}
/// structured response
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))]
pub struct GetYamlResponse {
@@ -537,7 +489,7 @@ impl std::str::FromStr for GetYamlResponse {
if let Some(key) = key_result {
match key {
"value" => intermediate_rep.value.push(String::from_str(val).map_err(|x| format!("{}", x))?),
"value" => intermediate_rep.value.push(<String as std::str::FromStr>::from_str(val).map_err(|x| format!("{}", x))?),
_ => return std::result::Result::Err("Unexpected key while parsing GetYamlResponse".to_string())
}
}
@@ -553,36 +505,34 @@ impl std::str::FromStr for GetYamlResponse {
}
}
// Methods for converting between header::IntoHeaderValue<InlineObject> and hyper::header::HeaderValue
// Methods for converting between header::IntoHeaderValue<GetYamlResponse> and hyper::header::HeaderValue
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<header::IntoHeaderValue<InlineObject>> for hyper::header::HeaderValue {
impl std::convert::TryFrom<header::IntoHeaderValue<GetYamlResponse>> for hyper::header::HeaderValue {
type Error = String;
fn try_from(hdr_value: header::IntoHeaderValue<InlineObject>) -> std::result::Result<Self, Self::Error> {
fn try_from(hdr_value: header::IntoHeaderValue<GetYamlResponse>) -> std::result::Result<Self, Self::Error> {
let hdr_value = hdr_value.to_string();
match hyper::header::HeaderValue::from_str(&hdr_value) {
std::result::Result::Ok(value) => std::result::Result::Ok(value),
std::result::Result::Err(e) => std::result::Result::Err(
format!("Invalid header value for InlineObject - value: {} is invalid {}",
format!("Invalid header value for GetYamlResponse - value: {} is invalid {}",
hdr_value, e))
}
}
}
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<hyper::header::HeaderValue> for header::IntoHeaderValue<InlineObject> {
impl std::convert::TryFrom<hyper::header::HeaderValue> for header::IntoHeaderValue<GetYamlResponse> {
type Error = String;
fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result<Self, Self::Error> {
match hdr_value.to_str() {
std::result::Result::Ok(value) => {
match <InlineObject as std::str::FromStr>::from_str(value) {
match <GetYamlResponse as std::str::FromStr>::from_str(value) {
std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)),
std::result::Result::Err(err) => std::result::Result::Err(
format!("Unable to convert header value '{}' into InlineObject - {}",
format!("Unable to convert header value '{}' into GetYamlResponse - {}",
value, err))
}
},
@@ -663,8 +613,8 @@ impl std::str::FromStr for InlineObject {
if let Some(key) = key_result {
match key {
"id" => intermediate_rep.id.push(String::from_str(val).map_err(|x| format!("{}", x))?),
"password" => intermediate_rep.password.push(String::from_str(val).map_err(|x| format!("{}", x))?),
"id" => intermediate_rep.id.push(<String as std::str::FromStr>::from_str(val).map_err(|x| format!("{}", x))?),
"password" => intermediate_rep.password.push(<String as std::str::FromStr>::from_str(val).map_err(|x| format!("{}", x))?),
_ => return std::result::Result::Err("Unexpected key while parsing InlineObject".to_string())
}
}
@@ -681,37 +631,34 @@ impl std::str::FromStr for InlineObject {
}
}
/// An object of objects
// Methods for converting between header::IntoHeaderValue<ObjectOfObjects> and hyper::header::HeaderValue
// Methods for converting between header::IntoHeaderValue<InlineObject> and hyper::header::HeaderValue
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<header::IntoHeaderValue<ObjectOfObjects>> for hyper::header::HeaderValue {
impl std::convert::TryFrom<header::IntoHeaderValue<InlineObject>> for hyper::header::HeaderValue {
type Error = String;
fn try_from(hdr_value: header::IntoHeaderValue<ObjectOfObjects>) -> std::result::Result<Self, Self::Error> {
fn try_from(hdr_value: header::IntoHeaderValue<InlineObject>) -> std::result::Result<Self, Self::Error> {
let hdr_value = hdr_value.to_string();
match hyper::header::HeaderValue::from_str(&hdr_value) {
std::result::Result::Ok(value) => std::result::Result::Ok(value),
std::result::Result::Err(e) => std::result::Result::Err(
format!("Invalid header value for ObjectOfObjects - value: {} is invalid {}",
format!("Invalid header value for InlineObject - value: {} is invalid {}",
hdr_value, e))
}
}
}
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<hyper::header::HeaderValue> for header::IntoHeaderValue<ObjectOfObjects> {
impl std::convert::TryFrom<hyper::header::HeaderValue> for header::IntoHeaderValue<InlineObject> {
type Error = String;
fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result<Self, Self::Error> {
match hdr_value.to_str() {
std::result::Result::Ok(value) => {
match <ObjectOfObjects as std::str::FromStr>::from_str(value) {
match <InlineObject as std::str::FromStr>::from_str(value) {
std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)),
std::result::Result::Err(err) => std::result::Result::Err(
format!("Unable to convert header value '{}' into ObjectOfObjects - {}",
format!("Unable to convert header value '{}' into InlineObject - {}",
value, err))
}
},
@@ -723,6 +670,7 @@ impl std::convert::TryFrom<hyper::header::HeaderValue> for header::IntoHeaderVal
}
/// An object of objects
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))]
pub struct ObjectOfObjects {
@@ -779,7 +727,7 @@ impl std::str::FromStr for ObjectOfObjects {
if let Some(key) = key_result {
match key {
"inner" => intermediate_rep.inner.push(models::ObjectOfObjectsInner::from_str(val).map_err(|x| format!("{}", x))?),
"inner" => intermediate_rep.inner.push(<models::ObjectOfObjectsInner as std::str::FromStr>::from_str(val).map_err(|x| format!("{}", x))?),
_ => return std::result::Result::Err("Unexpected key while parsing ObjectOfObjects".to_string())
}
}
@@ -795,36 +743,34 @@ impl std::str::FromStr for ObjectOfObjects {
}
}
// Methods for converting between header::IntoHeaderValue<ObjectOfObjectsInner> and hyper::header::HeaderValue
// Methods for converting between header::IntoHeaderValue<ObjectOfObjects> and hyper::header::HeaderValue
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<header::IntoHeaderValue<ObjectOfObjectsInner>> for hyper::header::HeaderValue {
impl std::convert::TryFrom<header::IntoHeaderValue<ObjectOfObjects>> for hyper::header::HeaderValue {
type Error = String;
fn try_from(hdr_value: header::IntoHeaderValue<ObjectOfObjectsInner>) -> std::result::Result<Self, Self::Error> {
fn try_from(hdr_value: header::IntoHeaderValue<ObjectOfObjects>) -> std::result::Result<Self, Self::Error> {
let hdr_value = hdr_value.to_string();
match hyper::header::HeaderValue::from_str(&hdr_value) {
std::result::Result::Ok(value) => std::result::Result::Ok(value),
std::result::Result::Err(e) => std::result::Result::Err(
format!("Invalid header value for ObjectOfObjectsInner - value: {} is invalid {}",
format!("Invalid header value for ObjectOfObjects - value: {} is invalid {}",
hdr_value, e))
}
}
}
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<hyper::header::HeaderValue> for header::IntoHeaderValue<ObjectOfObjectsInner> {
impl std::convert::TryFrom<hyper::header::HeaderValue> for header::IntoHeaderValue<ObjectOfObjects> {
type Error = String;
fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result<Self, Self::Error> {
match hdr_value.to_str() {
std::result::Result::Ok(value) => {
match <ObjectOfObjectsInner as std::str::FromStr>::from_str(value) {
match <ObjectOfObjects as std::str::FromStr>::from_str(value) {
std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)),
std::result::Result::Err(err) => std::result::Result::Err(
format!("Unable to convert header value '{}' into ObjectOfObjectsInner - {}",
format!("Unable to convert header value '{}' into ObjectOfObjects - {}",
value, err))
}
},
@@ -905,8 +851,8 @@ impl std::str::FromStr for ObjectOfObjectsInner {
if let Some(key) = key_result {
match key {
"required_thing" => intermediate_rep.required_thing.push(String::from_str(val).map_err(|x| format!("{}", x))?),
"optional_thing" => intermediate_rep.optional_thing.push(isize::from_str(val).map_err(|x| format!("{}", x))?),
"required_thing" => intermediate_rep.required_thing.push(<String as std::str::FromStr>::from_str(val).map_err(|x| format!("{}", x))?),
"optional_thing" => intermediate_rep.optional_thing.push(<isize as std::str::FromStr>::from_str(val).map_err(|x| format!("{}", x))?),
_ => return std::result::Result::Err("Unexpected key while parsing ObjectOfObjectsInner".to_string())
}
}
@@ -923,4 +869,41 @@ impl std::str::FromStr for ObjectOfObjectsInner {
}
}
// Methods for converting between header::IntoHeaderValue<ObjectOfObjectsInner> and hyper::header::HeaderValue
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<header::IntoHeaderValue<ObjectOfObjectsInner>> for hyper::header::HeaderValue {
type Error = String;
fn try_from(hdr_value: header::IntoHeaderValue<ObjectOfObjectsInner>) -> std::result::Result<Self, Self::Error> {
let hdr_value = hdr_value.to_string();
match hyper::header::HeaderValue::from_str(&hdr_value) {
std::result::Result::Ok(value) => std::result::Result::Ok(value),
std::result::Result::Err(e) => std::result::Result::Err(
format!("Invalid header value for ObjectOfObjectsInner - value: {} is invalid {}",
hdr_value, e))
}
}
}
#[cfg(any(feature = "client", feature = "server"))]
impl std::convert::TryFrom<hyper::header::HeaderValue> for header::IntoHeaderValue<ObjectOfObjectsInner> {
type Error = String;
fn try_from(hdr_value: hyper::header::HeaderValue) -> std::result::Result<Self, Self::Error> {
match hdr_value.to_str() {
std::result::Result::Ok(value) => {
match <ObjectOfObjectsInner as std::str::FromStr>::from_str(value) {
std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)),
std::result::Result::Err(err) => std::result::Result::Err(
format!("Unable to convert header value '{}' into ObjectOfObjectsInner - {}",
value, err))
}
},
std::result::Result::Err(e) => std::result::Result::Err(
format!("Unable to convert header: {:?} to string: {}",
hdr_value, e))
}
}
}