[Rust Server] Handle arrays in forms (#19625)

* [Rust Server] Handle arrays in forms correctly

* [Rust Server] Add tests

* Update samples
This commit is contained in:
Richard Whitehouse 2024-09-22 17:20:48 +01:00 committed by GitHub
parent 8821cf095e
commit fb36272358
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
14 changed files with 435 additions and 53 deletions

View File

@ -1520,6 +1520,10 @@ public class RustServerCodegen extends AbstractRustCodegen implements CodegenCon
if (Boolean.TRUE.equals(param.isFreeFormObject)) { if (Boolean.TRUE.equals(param.isFreeFormObject)) {
param.vendorExtensions.put("x-format-string", "{:?}"); param.vendorExtensions.put("x-format-string", "{:?}");
example = null; example = null;
} else if (param.isArray && param.isString) {
// This occurs if the parameter is a form property and is Vec<String>
param.vendorExtensions.put("x-format-string", "{:?}");
example = (param.example != null) ? "&vec![\"" + param.example + "\".to_string()]" : "&Vec::new()";
} else if (param.isString) { } else if (param.isString) {
param.vendorExtensions.put("x-format-string", "\\\"{}\\\""); param.vendorExtensions.put("x-format-string", "\\\"{}\\\"");
example = "\"" + ((param.example != null) ? param.example : "") + "\".to_string()"; example = "\"" + ((param.example != null) ? param.example : "") + "\".to_string()";

View File

@ -28,11 +28,36 @@
// Consumes form body // Consumes form body
{{#formParams}} {{#formParams}}
{{#-first}} {{#-first}}
let params = &[ let mut params = vec![];
{{/-first}} {{/-first}}
("{{{baseName}}}", {{#vendorExtensions}}{{#required}}Some({{#isString}}param_{{{paramName}}}{{/isString}}{{^isString}}format!("{:?}", param_{{{paramName}}}){{/isString}}){{/required}}{{^required}}{{#isString}}param_{{{paramName}}}{{/isString}}{{^isString}}param_{{{paramName}}}.map(|param| format!("{:?}", param)){{/isString}}{{/required}}{{/vendorExtensions}}), {{^required}}
if let Some(param_{{{paramName}}}) = param_{{{paramName}}} {
{{/required}}
{{#isArray}}
// style=form,explode=true
for param_{{{paramName}}} in param_{{{paramName}}} {
{{/isArray}}
params.push(("{{{baseName}}}",
{{^isString}}
format!("{{{vendorExtensions.x-format-string}}}", param_{{{paramName}}})
{{/isString}}
{{#isString}}
{{#isArray}}
param_{{{paramName}}}.to_string()
{{/isArray}}
{{^isArray}}
param_{{{paramName}}}
{{/isArray}}
{{/isString}}
));
{{#isArray}}
}
{{/isArray}}
{{^required}}
}
{{/required}}
{{#-last}} {{#-last}}
];
let body = serde_urlencoded::to_string(params).expect("impossible to fail to serialize"); let body = serde_urlencoded::to_string(params).expect("impossible to fail to serialize");
*request.body_mut() = Body::from(body.into_bytes()); *request.body_mut() = Body::from(body.into_bytes());

View File

@ -495,6 +495,24 @@ paths:
responses: responses:
200: 200:
description: OK description: OK
/form-test:
post:
summary: Test a Form Post
operationId: FormTest
requestBody:
content:
application/x-www-form-urlencoded:
schema:
type: object
properties:
requiredArray:
type: array
items:
type: string
required: true
responses:
'200':
description: OK
components: components:
securitySchemes: securitySchemes:

View File

@ -10,6 +10,7 @@ edition = "2018"
[features] [features]
default = ["client", "server"] default = ["client", "server"]
client = [ client = [
"serde_urlencoded",
"serde_ignored", "regex", "percent-encoding", "lazy_static", "serde_ignored", "regex", "percent-encoding", "lazy_static",
"hyper", "hyper-openssl", "hyper-tls", "native-tls", "openssl", "url" "hyper", "hyper-openssl", "hyper-tls", "native-tls", "openssl", "url"
] ]
@ -55,6 +56,7 @@ serde_ignored = {version = "0.1.1", optional = true}
url = {version = "2.1", optional = true} url = {version = "2.1", optional = true}
# Client-specific # Client-specific
serde_urlencoded = {version = "0.6.1", optional = true}
# Server, and client callback-specific # Server, and client callback-specific
lazy_static = { version = "1.4", optional = true } lazy_static = { version = "1.4", optional = true }

View File

@ -89,6 +89,7 @@ To run a client, follow one of the following simple steps:
cargo run --example client AnyOfGet cargo run --example client AnyOfGet
cargo run --example client CallbackWithHeaderPost cargo run --example client CallbackWithHeaderPost
cargo run --example client ComplexQueryParamGet cargo run --example client ComplexQueryParamGet
cargo run --example client FormTest
cargo run --example client GetWithBooleanParameter cargo run --example client GetWithBooleanParameter
cargo run --example client JsonComplexQueryParamGet cargo run --example client JsonComplexQueryParamGet
cargo run --example client MandatoryRequestHeaderGet cargo run --example client MandatoryRequestHeaderGet
@ -152,6 +153,7 @@ Method | HTTP request | Description
[****](docs/default_api.md#) | **GET** /any-of | [****](docs/default_api.md#) | **GET** /any-of |
[****](docs/default_api.md#) | **POST** /callback-with-header | [****](docs/default_api.md#) | **POST** /callback-with-header |
[****](docs/default_api.md#) | **GET** /complex-query-param | [****](docs/default_api.md#) | **GET** /complex-query-param |
[**FormTest**](docs/default_api.md#FormTest) | **POST** /form-test | Test a Form Post
[**GetWithBooleanParameter**](docs/default_api.md#GetWithBooleanParameter) | **GET** /get-with-bool | [**GetWithBooleanParameter**](docs/default_api.md#GetWithBooleanParameter) | **GET** /get-with-bool |
[****](docs/default_api.md#) | **GET** /json-complex-query-param | [****](docs/default_api.md#) | **GET** /json-complex-query-param |
[****](docs/default_api.md#) | **GET** /mandatory-request-header | [****](docs/default_api.md#) | **GET** /mandatory-request-header |

View File

@ -525,6 +525,19 @@ paths:
responses: responses:
"200": "200":
description: OK description: OK
/form-test:
post:
operationId: FormTest
requestBody:
content:
application/x-www-form-urlencoded:
schema:
$ref: '#/components/schemas/FormTest_request'
required: true
responses:
"200":
description: OK
summary: Test a Form Post
components: components:
schemas: schemas:
AnyOfProperty: AnyOfProperty:
@ -780,6 +793,13 @@ components:
anyOf: anyOf:
- $ref: '#/components/schemas/StringObject' - $ref: '#/components/schemas/StringObject'
- $ref: '#/components/schemas/UuidObject' - $ref: '#/components/schemas/UuidObject'
FormTest_request:
properties:
requiredArray:
items:
type: string
type: array
type: object
AnyOfObject_anyOf: AnyOfObject_anyOf:
enum: enum:
- FOO - FOO

View File

@ -8,6 +8,7 @@ use openapi_v3::{
AnyOfGetResponse, AnyOfGetResponse,
CallbackWithHeaderPostResponse, CallbackWithHeaderPostResponse,
ComplexQueryParamGetResponse, ComplexQueryParamGetResponse,
FormTestResponse,
GetWithBooleanParameterResponse, GetWithBooleanParameterResponse,
JsonComplexQueryParamGetResponse, JsonComplexQueryParamGetResponse,
MandatoryRequestHeaderGetResponse, MandatoryRequestHeaderGetResponse,
@ -101,6 +102,11 @@ enum Operation {
#[structopt(parse(try_from_str = parse_json), long)] #[structopt(parse(try_from_str = parse_json), long)]
list_of_strings: Option<Vec<models::StringObject>>, list_of_strings: Option<Vec<models::StringObject>>,
}, },
/// Test a Form Post
FormTest {
#[structopt(parse(try_from_str = parse_json), long)]
required_array: Option<Vec<String>>,
},
GetWithBooleanParameter { GetWithBooleanParameter {
/// Let's check apostrophes get encoded properly! /// Let's check apostrophes get encoded properly!
#[structopt(short, long)] #[structopt(short, long)]
@ -319,6 +325,22 @@ async fn main() -> Result<()> {
, ,
} }
} }
Operation::FormTest {
required_array,
} => {
info!("Performing a FormTest request");
let result = client.form_test(
required_array.as_ref(),
).await?;
debug!("Result: {:?}", result);
match result {
FormTestResponse::OK
=> "OK\n".to_string()
,
}
}
Operation::GetWithBooleanParameter { Operation::GetWithBooleanParameter {
iambool, iambool,
} => { } => {

View File

@ -7,6 +7,7 @@ Method | HTTP request | Description
****](default_api.md#) | **GET** /any-of | ****](default_api.md#) | **GET** /any-of |
****](default_api.md#) | **POST** /callback-with-header | ****](default_api.md#) | **POST** /callback-with-header |
****](default_api.md#) | **GET** /complex-query-param | ****](default_api.md#) | **GET** /complex-query-param |
**FormTest**](default_api.md#FormTest) | **POST** /form-test | Test a Form Post
**GetWithBooleanParameter**](default_api.md#GetWithBooleanParameter) | **GET** /get-with-bool | **GetWithBooleanParameter**](default_api.md#GetWithBooleanParameter) | **GET** /get-with-bool |
****](default_api.md#) | **GET** /json-complex-query-param | ****](default_api.md#) | **GET** /json-complex-query-param |
****](default_api.md#) | **GET** /mandatory-request-header | ****](default_api.md#) | **GET** /mandatory-request-header |
@ -122,6 +123,38 @@ No authorization required
[[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) [[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)
# **FormTest**
> FormTest(optional)
Test a Form Post
### 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
------------- | ------------- | ------------- | -------------
**required_array** | [**String**](String.md)| |
### Return type
(empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/x-www-form-urlencoded
- **Accept**: Not defined
[[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)
# **GetWithBooleanParameter** # **GetWithBooleanParameter**
> GetWithBooleanParameter(iambool) > GetWithBooleanParameter(iambool)

View File

@ -9,6 +9,7 @@ use openapi_v3::{Api, ApiNoContext, Claims, Client, ContextWrapperExt, models,
AnyOfGetResponse, AnyOfGetResponse,
CallbackWithHeaderPostResponse, CallbackWithHeaderPostResponse,
ComplexQueryParamGetResponse, ComplexQueryParamGetResponse,
FormTestResponse,
GetWithBooleanParameterResponse, GetWithBooleanParameterResponse,
JsonComplexQueryParamGetResponse, JsonComplexQueryParamGetResponse,
MandatoryRequestHeaderGetResponse, MandatoryRequestHeaderGetResponse,
@ -66,6 +67,7 @@ fn main() {
"AnyOfGet", "AnyOfGet",
"CallbackWithHeaderPost", "CallbackWithHeaderPost",
"ComplexQueryParamGet", "ComplexQueryParamGet",
"FormTest",
"GetWithBooleanParameter", "GetWithBooleanParameter",
"JsonComplexQueryParamGet", "JsonComplexQueryParamGet",
"MandatoryRequestHeaderGet", "MandatoryRequestHeaderGet",
@ -185,6 +187,12 @@ fn main() {
)); ));
info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has<XSpanIdString>).get().clone()); info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has<XSpanIdString>).get().clone());
}, },
Some("FormTest") => {
let result = rt.block_on(client.form_test(
Some(&Vec::new())
));
info!("{:?} (X-Span-ID: {:?})", result, (client.context() as &dyn Has<XSpanIdString>).get().clone());
},
Some("GetWithBooleanParameter") => { Some("GetWithBooleanParameter") => {
let result = rt.block_on(client.get_with_boolean_parameter( let result = rt.block_on(client.get_with_boolean_parameter(
true true

View File

@ -105,6 +105,7 @@ use openapi_v3::{
AnyOfGetResponse, AnyOfGetResponse,
CallbackWithHeaderPostResponse, CallbackWithHeaderPostResponse,
ComplexQueryParamGetResponse, ComplexQueryParamGetResponse,
FormTestResponse,
GetWithBooleanParameterResponse, GetWithBooleanParameterResponse,
JsonComplexQueryParamGetResponse, JsonComplexQueryParamGetResponse,
MandatoryRequestHeaderGetResponse, MandatoryRequestHeaderGetResponse,
@ -166,6 +167,16 @@ impl<C> Api<C> for Server<C> where C: Has<XSpanIdString> + Send + Sync
Err(ApiError("Api-Error: Operation is NOT implemented".into())) Err(ApiError("Api-Error: Operation is NOT implemented".into()))
} }
/// Test a Form Post
async fn form_test(
&self,
required_array: Option<&Vec<String>>,
context: &C) -> Result<FormTestResponse, ApiError>
{
info!("form_test({:?}) - X-Span-ID: {:?}", required_array, context.get().0.clone());
Err(ApiError("Api-Error: Operation is NOT implemented".into()))
}
async fn get_with_boolean_parameter( async fn get_with_boolean_parameter(
&self, &self,
iambool: bool, iambool: bool,

View File

@ -39,6 +39,7 @@ use crate::{Api,
AnyOfGetResponse, AnyOfGetResponse,
CallbackWithHeaderPostResponse, CallbackWithHeaderPostResponse,
ComplexQueryParamGetResponse, ComplexQueryParamGetResponse,
FormTestResponse,
GetWithBooleanParameterResponse, GetWithBooleanParameterResponse,
JsonComplexQueryParamGetResponse, JsonComplexQueryParamGetResponse,
MandatoryRequestHeaderGetResponse, MandatoryRequestHeaderGetResponse,
@ -670,6 +671,96 @@ impl<S, C> Api<C> for Client<S, C> where
} }
} }
async fn form_test(
&self,
param_required_array: Option<&Vec<String>>,
context: &C) -> Result<FormTestResponse, ApiError>
{
let mut client_service = self.client_service.clone();
let mut uri = format!(
"{}/form-test",
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("POST")
.uri(uri)
.body(Body::empty()) {
Ok(req) => req,
Err(e) => return Err(ApiError(format!("Unable to create request: {}", e)))
};
// Consumes form body
let mut params = vec![];
if let Some(param_required_array) = param_required_array {
// style=form,explode=true
for param_required_array in param_required_array {
params.push(("requiredArray",
format!("{:?}", param_required_array)
));
}
}
let body = serde_urlencoded::to_string(params).expect("impossible to fail to serialize");
*request.body_mut() = Body::from(body.into_bytes());
let header = "application/x-www-form-urlencoded";
request.headers_mut().insert(CONTENT_TYPE, match HeaderValue::from_str(header) {
Ok(h) => h,
Err(e) => return Err(ApiError(format!("Unable to create header: {} - {}", header, e)))
});
let header = HeaderValue::from_str(Has::<XSpanIdString>::get(context).0.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 response = client_service.call((request, context.clone()))
.map_err(|e| ApiError(format!("No response received: {}", e))).await?;
match response.status().as_u16() {
200 => {
Ok(
FormTestResponse::OK
)
}
code => {
let headers = response.headers().clone();
let body = response.into_body()
.take(100)
.into_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 get_with_boolean_parameter( async fn get_with_boolean_parameter(
&self, &self,
param_iambool: bool, param_iambool: bool,

View File

@ -48,6 +48,12 @@ pub enum ComplexQueryParamGetResponse {
Success Success
} }
#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub enum FormTestResponse {
/// OK
OK
}
#[derive(Debug, PartialEq, Serialize, Deserialize)] #[derive(Debug, PartialEq, Serialize, Deserialize)]
pub enum GetWithBooleanParameterResponse { pub enum GetWithBooleanParameterResponse {
/// OK /// OK
@ -319,6 +325,12 @@ pub trait Api<C: Send + Sync> {
list_of_strings: Option<&Vec<models::StringObject>>, list_of_strings: Option<&Vec<models::StringObject>>,
context: &C) -> Result<ComplexQueryParamGetResponse, ApiError>; context: &C) -> Result<ComplexQueryParamGetResponse, ApiError>;
/// Test a Form Post
async fn form_test(
&self,
required_array: Option<&Vec<String>>,
context: &C) -> Result<FormTestResponse, ApiError>;
async fn get_with_boolean_parameter( async fn get_with_boolean_parameter(
&self, &self,
iambool: bool, iambool: bool,
@ -473,6 +485,12 @@ pub trait ApiNoContext<C: Send + Sync> {
list_of_strings: Option<&Vec<models::StringObject>>, list_of_strings: Option<&Vec<models::StringObject>>,
) -> Result<ComplexQueryParamGetResponse, ApiError>; ) -> Result<ComplexQueryParamGetResponse, ApiError>;
/// Test a Form Post
async fn form_test(
&self,
required_array: Option<&Vec<String>>,
) -> Result<FormTestResponse, ApiError>;
async fn get_with_boolean_parameter( async fn get_with_boolean_parameter(
&self, &self,
iambool: bool, iambool: bool,
@ -653,6 +671,16 @@ impl<T: Api<C> + Send + Sync, C: Clone + Send + Sync> ApiNoContext<C> for Contex
self.api().complex_query_param_get(list_of_strings, &context).await self.api().complex_query_param_get(list_of_strings, &context).await
} }
/// Test a Form Post
async fn form_test(
&self,
required_array: Option<&Vec<String>>,
) -> Result<FormTestResponse, ApiError>
{
let context = self.context().clone();
self.api().form_test(required_array, &context).await
}
async fn get_with_boolean_parameter( async fn get_with_boolean_parameter(
&self, &self,
iambool: bool, iambool: bool,

View File

@ -24,6 +24,7 @@ use crate::{Api,
AnyOfGetResponse, AnyOfGetResponse,
CallbackWithHeaderPostResponse, CallbackWithHeaderPostResponse,
ComplexQueryParamGetResponse, ComplexQueryParamGetResponse,
FormTestResponse,
GetWithBooleanParameterResponse, GetWithBooleanParameterResponse,
JsonComplexQueryParamGetResponse, JsonComplexQueryParamGetResponse,
MandatoryRequestHeaderGetResponse, MandatoryRequestHeaderGetResponse,
@ -65,6 +66,7 @@ mod paths {
r"^/callback-with-header$", r"^/callback-with-header$",
r"^/complex-query-param$", r"^/complex-query-param$",
r"^/enum_in_path/(?P<path_param>[^/?#]*)$", r"^/enum_in_path/(?P<path_param>[^/?#]*)$",
r"^/form-test$",
r"^/get-with-bool$", r"^/get-with-bool$",
r"^/json-complex-query-param$", r"^/json-complex-query-param$",
r"^/mandatory-request-header$", r"^/mandatory-request-header$",
@ -101,41 +103,42 @@ mod paths {
regex::Regex::new(r"^/enum_in_path/(?P<path_param>[^/?#]*)$") regex::Regex::new(r"^/enum_in_path/(?P<path_param>[^/?#]*)$")
.expect("Unable to create regex for ENUM_IN_PATH_PATH_PARAM"); .expect("Unable to create regex for ENUM_IN_PATH_PATH_PARAM");
} }
pub(crate) static ID_GET_WITH_BOOL: usize = 4; pub(crate) static ID_FORM_TEST: usize = 4;
pub(crate) static ID_JSON_COMPLEX_QUERY_PARAM: usize = 5; pub(crate) static ID_GET_WITH_BOOL: usize = 5;
pub(crate) static ID_MANDATORY_REQUEST_HEADER: usize = 6; pub(crate) static ID_JSON_COMPLEX_QUERY_PARAM: usize = 6;
pub(crate) static ID_MERGE_PATCH_JSON: usize = 7; pub(crate) static ID_MANDATORY_REQUEST_HEADER: usize = 7;
pub(crate) static ID_MULTIGET: usize = 8; pub(crate) static ID_MERGE_PATCH_JSON: usize = 8;
pub(crate) static ID_MULTIPLE_PATH_PARAMS_WITH_VERY_LONG_PATH_TO_TEST_FORMATTING_PATH_PARAM_A_PATH_PARAM_B: usize = 9; pub(crate) static ID_MULTIGET: usize = 9;
pub(crate) static ID_MULTIPLE_PATH_PARAMS_WITH_VERY_LONG_PATH_TO_TEST_FORMATTING_PATH_PARAM_A_PATH_PARAM_B: usize = 10;
lazy_static! { lazy_static! {
pub static ref REGEX_MULTIPLE_PATH_PARAMS_WITH_VERY_LONG_PATH_TO_TEST_FORMATTING_PATH_PARAM_A_PATH_PARAM_B: regex::Regex = pub static ref REGEX_MULTIPLE_PATH_PARAMS_WITH_VERY_LONG_PATH_TO_TEST_FORMATTING_PATH_PARAM_A_PATH_PARAM_B: regex::Regex =
#[allow(clippy::invalid_regex)] #[allow(clippy::invalid_regex)]
regex::Regex::new(r"^/multiple-path-params-with-very-long-path-to-test-formatting/(?P<path_param_a>[^/?#]*)/(?P<path_param_b>[^/?#]*)$") regex::Regex::new(r"^/multiple-path-params-with-very-long-path-to-test-formatting/(?P<path_param_a>[^/?#]*)/(?P<path_param_b>[^/?#]*)$")
.expect("Unable to create regex for MULTIPLE_PATH_PARAMS_WITH_VERY_LONG_PATH_TO_TEST_FORMATTING_PATH_PARAM_A_PATH_PARAM_B"); .expect("Unable to create regex for MULTIPLE_PATH_PARAMS_WITH_VERY_LONG_PATH_TO_TEST_FORMATTING_PATH_PARAM_A_PATH_PARAM_B");
} }
pub(crate) static ID_MULTIPLE_AUTH_SCHEME: usize = 10; pub(crate) static ID_MULTIPLE_AUTH_SCHEME: usize = 11;
pub(crate) static ID_ONE_OF: usize = 11; pub(crate) static ID_ONE_OF: usize = 12;
pub(crate) static ID_OPERATION_TWO_FIRST_LETTER_HEADERS: usize = 12; pub(crate) static ID_OPERATION_TWO_FIRST_LETTER_HEADERS: usize = 13;
pub(crate) static ID_OVERRIDE_SERVER: usize = 13; pub(crate) static ID_OVERRIDE_SERVER: usize = 14;
pub(crate) static ID_PARAMGET: usize = 14; pub(crate) static ID_PARAMGET: usize = 15;
pub(crate) static ID_READONLY_AUTH_SCHEME: usize = 15; pub(crate) static ID_READONLY_AUTH_SCHEME: usize = 16;
pub(crate) static ID_REGISTER_CALLBACK: usize = 16; pub(crate) static ID_REGISTER_CALLBACK: usize = 17;
pub(crate) static ID_REPOS: usize = 17; pub(crate) static ID_REPOS: usize = 18;
pub(crate) static ID_REPOS_REPOID: usize = 18; pub(crate) static ID_REPOS_REPOID: usize = 19;
lazy_static! { lazy_static! {
pub static ref REGEX_REPOS_REPOID: regex::Regex = pub static ref REGEX_REPOS_REPOID: regex::Regex =
#[allow(clippy::invalid_regex)] #[allow(clippy::invalid_regex)]
regex::Regex::new(r"^/repos/(?P<repoId>[^/?#]*)$") regex::Regex::new(r"^/repos/(?P<repoId>[^/?#]*)$")
.expect("Unable to create regex for REPOS_REPOID"); .expect("Unable to create regex for REPOS_REPOID");
} }
pub(crate) static ID_REQUIRED_OCTET_STREAM: usize = 19; pub(crate) static ID_REQUIRED_OCTET_STREAM: usize = 20;
pub(crate) static ID_RESPONSES_WITH_HEADERS: usize = 20; pub(crate) static ID_RESPONSES_WITH_HEADERS: usize = 21;
pub(crate) static ID_RFC7807: usize = 21; pub(crate) static ID_RFC7807: usize = 22;
pub(crate) static ID_UNTYPED_PROPERTY: usize = 22; pub(crate) static ID_UNTYPED_PROPERTY: usize = 23;
pub(crate) static ID_UUID: usize = 23; pub(crate) static ID_UUID: usize = 24;
pub(crate) static ID_XML: usize = 24; pub(crate) static ID_XML: usize = 25;
pub(crate) static ID_XML_EXTRA: usize = 25; pub(crate) static ID_XML_EXTRA: usize = 26;
pub(crate) static ID_XML_OTHER: usize = 26; pub(crate) static ID_XML_OTHER: usize = 27;
} }
@ -421,6 +424,54 @@ impl<T, C> hyper::service::Service<(Request<Body>, C)> for Service<T, C> where
Ok(response) Ok(response)
}, },
// FormTest - POST /form-test
hyper::Method::POST if path.matched(paths::ID_FORM_TEST) => {
// Handle body parameters (note that non-required body parameters will ignore garbage
// values, rather than causing a 400 response). Produce warning header and logs for
// any unused fields.
let result = body.into_raw().await;
match result {
Ok(body) => {
// Form parameters
let param_required_array =
None;
let result = api_impl.form_test(
param_required_array.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().as_str())
.expect("Unable to create X-Span-ID header value"));
match result {
Ok(rsp) => match rsp {
FormTestResponse::OK
=> {
*response.status_mut() = StatusCode::from_u16(200).expect("Unable to turn 200 into a StatusCode");
},
},
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)
},
Err(e) => Ok(Response::builder()
.status(StatusCode::BAD_REQUEST)
.body(Body::from(format!("Unable to read body: {}", e)))
.expect("Unable to create Bad Request response due to unable to read body")),
}
},
// GetWithBooleanParameter - GET /get-with-bool // GetWithBooleanParameter - GET /get-with-bool
hyper::Method::GET if path.matched(paths::ID_GET_WITH_BOOL) => { hyper::Method::GET if path.matched(paths::ID_GET_WITH_BOOL) => {
// Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response) // Query parameters (note that non-required or collection query parameters will ignore garbage values, rather than causing a 400 response)
@ -2126,6 +2177,7 @@ impl<T, C> hyper::service::Service<(Request<Body>, C)> for Service<T, C> where
_ if path.matched(paths::ID_CALLBACK_WITH_HEADER) => 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_COMPLEX_QUERY_PARAM) => method_not_allowed(),
_ if path.matched(paths::ID_ENUM_IN_PATH_PATH_PARAM) => method_not_allowed(), _ if path.matched(paths::ID_ENUM_IN_PATH_PATH_PARAM) => method_not_allowed(),
_ if path.matched(paths::ID_FORM_TEST) => method_not_allowed(),
_ if path.matched(paths::ID_GET_WITH_BOOL) => method_not_allowed(), _ if path.matched(paths::ID_GET_WITH_BOOL) => method_not_allowed(),
_ if path.matched(paths::ID_JSON_COMPLEX_QUERY_PARAM) => method_not_allowed(), _ if path.matched(paths::ID_JSON_COMPLEX_QUERY_PARAM) => method_not_allowed(),
_ if path.matched(paths::ID_MANDATORY_REQUEST_HEADER) => method_not_allowed(), _ if path.matched(paths::ID_MANDATORY_REQUEST_HEADER) => method_not_allowed(),
@ -2173,6 +2225,8 @@ impl<T> RequestParser<T> for ApiRequestParser {
hyper::Method::POST if path.matched(paths::ID_CALLBACK_WITH_HEADER) => Some("CallbackWithHeaderPost"), hyper::Method::POST if path.matched(paths::ID_CALLBACK_WITH_HEADER) => Some("CallbackWithHeaderPost"),
// ComplexQueryParamGet - GET /complex-query-param // ComplexQueryParamGet - GET /complex-query-param
hyper::Method::GET if path.matched(paths::ID_COMPLEX_QUERY_PARAM) => Some("ComplexQueryParamGet"), hyper::Method::GET if path.matched(paths::ID_COMPLEX_QUERY_PARAM) => Some("ComplexQueryParamGet"),
// FormTest - POST /form-test
hyper::Method::POST if path.matched(paths::ID_FORM_TEST) => Some("FormTest"),
// GetWithBooleanParameter - GET /get-with-bool // GetWithBooleanParameter - GET /get-with-bool
hyper::Method::GET if path.matched(paths::ID_GET_WITH_BOOL) => Some("GetWithBooleanParameter"), hyper::Method::GET if path.matched(paths::ID_GET_WITH_BOOL) => Some("GetWithBooleanParameter"),
// JsonComplexQueryParamGet - GET /json-complex-query-param // JsonComplexQueryParamGet - GET /json-complex-query-param

View File

@ -1238,22 +1238,70 @@ impl<S, C> Api<C> for Client<S, C> where
}; };
// Consumes form body // Consumes form body
let params = &[ let mut params = vec![];
("integer", param_integer.map(|param| format!("{:?}", param))), if let Some(param_integer) = param_integer {
("int32", param_int32.map(|param| format!("{:?}", param))), params.push(("integer",
("int64", param_int64.map(|param| format!("{:?}", param))), format!("{:?}", param_integer)
("number", Some(format!("{:?}", param_number))), ));
("float", param_float.map(|param| format!("{:?}", param))), }
("double", Some(format!("{:?}", param_double))), if let Some(param_int32) = param_int32 {
("string", param_string), params.push(("int32",
("pattern_without_delimiter", Some(param_pattern_without_delimiter)), format!("{:?}", param_int32)
("byte", Some(format!("{:?}", param_byte))), ));
("binary", param_binary.map(|param| format!("{:?}", param))), }
("date", param_date.map(|param| format!("{:?}", param))), if let Some(param_int64) = param_int64 {
("dateTime", param_date_time.map(|param| format!("{:?}", param))), params.push(("int64",
("password", param_password), format!("{:?}", param_int64)
("callback", param_callback), ));
]; }
params.push(("number",
format!("{}", param_number)
));
if let Some(param_float) = param_float {
params.push(("float",
format!("{:?}", param_float)
));
}
params.push(("double",
format!("{}", param_double)
));
if let Some(param_string) = param_string {
params.push(("string",
param_string
));
}
params.push(("pattern_without_delimiter",
param_pattern_without_delimiter
));
params.push(("byte",
format!("{:?}", param_byte)
));
if let Some(param_binary) = param_binary {
params.push(("binary",
format!("{:?}", param_binary)
));
}
if let Some(param_date) = param_date {
params.push(("date",
format!("{:?}", param_date)
));
}
if let Some(param_date_time) = param_date_time {
params.push(("dateTime",
format!("{:?}", param_date_time)
));
}
if let Some(param_password) = param_password {
params.push(("password",
param_password
));
}
if let Some(param_callback) = param_callback {
params.push(("callback",
param_callback
));
}
let body = serde_urlencoded::to_string(params).expect("impossible to fail to serialize"); let body = serde_urlencoded::to_string(params).expect("impossible to fail to serialize");
*request.body_mut() = Body::from(body.into_bytes()); *request.body_mut() = Body::from(body.into_bytes());
@ -1379,9 +1427,13 @@ impl<S, C> Api<C> for Client<S, C> where
}; };
// Consumes form body // Consumes form body
let params = &[ let mut params = vec![];
("enum_form_string", param_enum_form_string.map(|param| format!("{:?}", param))), if let Some(param_enum_form_string) = param_enum_form_string {
]; params.push(("enum_form_string",
format!("{:?}", param_enum_form_string)
));
}
let body = serde_urlencoded::to_string(params).expect("impossible to fail to serialize"); let body = serde_urlencoded::to_string(params).expect("impossible to fail to serialize");
*request.body_mut() = Body::from(body.into_bytes()); *request.body_mut() = Body::from(body.into_bytes());
@ -1583,10 +1635,14 @@ impl<S, C> Api<C> for Client<S, C> where
}; };
// Consumes form body // Consumes form body
let params = &[ let mut params = vec![];
("param", Some(param_param)), params.push(("param",
("param2", Some(param_param2)), param_param
]; ));
params.push(("param2",
param_param2
));
let body = serde_urlencoded::to_string(params).expect("impossible to fail to serialize"); let body = serde_urlencoded::to_string(params).expect("impossible to fail to serialize");
*request.body_mut() = Body::from(body.into_bytes()); *request.body_mut() = Body::from(body.into_bytes());
@ -2470,10 +2526,18 @@ impl<S, C> Api<C> for Client<S, C> where
}; };
// Consumes form body // Consumes form body
let params = &[ let mut params = vec![];
("name", param_name), if let Some(param_name) = param_name {
("status", param_status), params.push(("name",
]; param_name
));
}
if let Some(param_status) = param_status {
params.push(("status",
param_status
));
}
let body = serde_urlencoded::to_string(params).expect("impossible to fail to serialize"); let body = serde_urlencoded::to_string(params).expect("impossible to fail to serialize");
*request.body_mut() = Body::from(body.into_bytes()); *request.body_mut() = Body::from(body.into_bytes());