[rust] Update to modern hyper and futures crates (#9919)

* [rust] Update to modern hyper and futures crates

* [rust] Update to modern hyper and futures crates
This commit is contained in:
Sheldon Young 2021-11-24 01:20:44 -08:00 committed by GitHub
parent af0babf892
commit d01ad0524c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 409 additions and 405 deletions

View File

@ -10,10 +10,12 @@ serde_derive = "^1.0"
serde_json = "^1.0" serde_json = "^1.0"
url = "^2.2" url = "^2.2"
{{#hyper}} {{#hyper}}
hyper = "~0.11" hyper = { version = "~0.14", features = ["full"] }
hyper-tls = "~0.5"
http = "~0.2"
serde_yaml = "0.7" serde_yaml = "0.7"
base64 = "~0.7.0" base64 = "~0.7.0"
futures = "0.1.23" futures = "^0.3"
{{/hyper}} {{/hyper}}
{{#reqwest}} {{#reqwest}}
{{^supportAsync}} {{^supportAsync}}

View File

@ -1,21 +1,23 @@
{{>partial_header}} {{>partial_header}}
use std::rc::Rc; use std::rc::Rc;
use std::borrow::Borrow; use std::borrow::Borrow;
use std::pin::Pin;
#[allow(unused_imports)] #[allow(unused_imports)]
use std::option::Option; use std::option::Option;
use hyper; use hyper;
use serde_json;
use futures::Future; use futures::Future;
use super::{Error, configuration}; use super::{Error, configuration};
use super::request as __internal_request; use super::request as __internal_request;
pub struct {{{classname}}}Client<C: hyper::client::Connect> { pub struct {{{classname}}}Client<C: hyper::client::connect::Connect>
where C: Clone + std::marker::Send + Sync + 'static {
configuration: Rc<configuration::Configuration<C>>, configuration: Rc<configuration::Configuration<C>>,
} }
impl<C: hyper::client::Connect> {{{classname}}}Client<C> { impl<C: hyper::client::connect::Connect> {{{classname}}}Client<C>
where C: Clone + std::marker::Send + Sync {
pub fn new(configuration: Rc<configuration::Configuration<C>>) -> {{{classname}}}Client<C> { pub fn new(configuration: Rc<configuration::Configuration<C>>) -> {{{classname}}}Client<C> {
{{{classname}}}Client { {{{classname}}}Client {
configuration, configuration,
@ -26,16 +28,18 @@ impl<C: hyper::client::Connect> {{{classname}}}Client<C> {
pub trait {{{classname}}} { pub trait {{{classname}}} {
{{#operations}} {{#operations}}
{{#operation}} {{#operation}}
fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}crate::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> Box<dyn Future<Item = {{^returnType}}(){{/returnType}}{{{returnType}}}, Error = Error<serde_json::Value>>>; fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}crate::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> Pin<Box<dyn Future<Output = Result<{{^returnType}}(){{/returnType}}{{#returnType}}{{{returnType}}}{{/returnType}}, Error>>>>;
{{/operation}} {{/operation}}
{{/operations}} {{/operations}}
} }
impl<C: hyper::client::Connect>{{{classname}}} for {{{classname}}}Client<C> { impl<C: hyper::client::connect::Connect>{{{classname}}} for {{{classname}}}Client<C>
{{#operations}} where C: Clone + std::marker::Send + Sync {
{{#operation}} {{#operations}}
fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isString}}{{^isUuid}}&str{{/isUuid}}{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}crate::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> Box<dyn Future<Item = {{^returnType}}(){{/returnType}}{{{returnType}}}, Error = Error<serde_json::Value>>> { {{#operation}}
let mut req = __internal_request::Request::new(hyper::Method::{{{httpMethod}}}, "{{{path}}}".to_string()) #[allow(unused_mut)]
fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}crate::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> Pin<Box<dyn Future<Output = Result<{{^returnType}}(){{/returnType}}{{#returnType}}{{{.}}}{{/returnType}}, Error>>>> {
let mut req = __internal_request::Request::new(hyper::Method::{{{httpMethod.toUpperCase}}}, "{{{path}}}".to_string())
{{#hasAuthMethods}} {{#hasAuthMethods}}
{{#authMethods}} {{#authMethods}}
{{#isApiKey}} {{#isApiKey}}
@ -68,7 +72,8 @@ impl<C: hyper::client::Connect>{{{classname}}} for {{{classname}}}Client<C> {
{{/required}} {{/required}}
{{^required}} {{^required}}
if let Some(ref s) = {{{paramName}}} { if let Some(ref s) = {{{paramName}}} {
req = req.with_query_param("{{{baseName}}}".to_string(), s{{#isArray}}.join(","){{/isArray}}.to_string()); let query_value = {{#isArray}}s.iter().map(|s| s.to_string()).collect::<Vec<String>>().join(","){{/isArray}}{{^isArray}}s.to_string(){{/isArray}};
req = req.with_query_param("{{{baseName}}}".to_string(), query_value);
} }
{{/required}} {{/required}}
{{/queryParams}} {{/queryParams}}

View File

@ -1,49 +1,45 @@
use http;
use hyper; use hyper;
use serde;
use serde_json; use serde_json;
#[derive(Debug)] #[derive(Debug)]
pub enum Error<T> { pub enum Error {
UriError(hyper::error::UriError), Api(ApiError),
Header(hyper::http::header::InvalidHeaderValue),
Http(http::Error),
Hyper(hyper::Error), Hyper(hyper::Error),
Serde(serde_json::Error), Serde(serde_json::Error),
ApiError(ApiError<T>), UriError(http::uri::InvalidUri),
} }
#[derive(Debug)] #[derive(Debug)]
pub struct ApiError<T> { pub struct ApiError {
pub code: hyper::StatusCode, pub code: hyper::StatusCode,
pub content: Option<T>, pub body: hyper::body::Body,
} }
impl<'de, T> From<(hyper::StatusCode, &'de [u8])> for Error<T> impl From<(hyper::StatusCode, hyper::body::Body)> for Error {
where T: serde::Deserialize<'de> { fn from(e: (hyper::StatusCode, hyper::body::Body)) -> Self {
fn from(e: (hyper::StatusCode, &'de [u8])) -> Self { Error::Api(ApiError {
if e.1.len() == 0 { code: e.0,
return Error::ApiError(ApiError{ body: e.1,
code: e.0, })
content: None,
});
}
match serde_json::from_slice::<T>(e.1) {
Ok(t) => Error::ApiError(ApiError{
code: e.0,
content: Some(t),
}),
Err(e) => {
Error::from(e)
}
}
} }
} }
impl<T> From<hyper::Error> for Error<T> { impl From<http::Error> for Error {
fn from(e: http::Error) -> Self {
return Error::Http(e)
}
}
impl From<hyper::Error> for Error {
fn from(e: hyper::Error) -> Self { fn from(e: hyper::Error) -> Self {
return Error::Hyper(e) return Error::Hyper(e)
} }
} }
impl<T> From<serde_json::Error> for Error<T> { impl From<serde_json::Error> for Error {
fn from(e: serde_json::Error) -> Self { fn from(e: serde_json::Error) -> Self {
return Error::Serde(e) return Error::Serde(e)
} }

View File

@ -18,7 +18,8 @@ pub struct APIClient {
} }
impl APIClient { impl APIClient {
pub fn new<C: hyper::client::Connect>(configuration: Configuration<C>) -> APIClient { pub fn new<C: hyper::client::connect::Connect>(configuration: Configuration<C>) -> APIClient
where C: Clone + std::marker::Send + Sync + 'static {
let rc = Rc::new(configuration); let rc = Rc::new(configuration);
APIClient { APIClient {

View File

@ -1,7 +1,8 @@
{{>partial_header}} {{>partial_header}}
use hyper; use hyper;
pub struct Configuration<C: hyper::client::Connect> { pub struct Configuration<C: hyper::client::connect::Connect>
where C: Clone + std::marker::Send + Sync + 'static {
pub base_path: String, pub base_path: String,
pub user_agent: Option<String>, pub user_agent: Option<String>,
pub client: hyper::client::Client<C>, pub client: hyper::client::Client<C>,
@ -18,12 +19,13 @@ pub struct ApiKey {
pub key: String, pub key: String,
} }
impl<C: hyper::client::Connect> Configuration<C> { impl<C: hyper::client::connect::Connect> Configuration<C>
where C: Clone + std::marker::Send + Sync {
pub fn new(client: hyper::client::Client<C>) -> Configuration<C> { pub fn new(client: hyper::client::Client<C>) -> Configuration<C> {
Configuration { Configuration {
base_path: "{{{basePath}}}".to_owned(), base_path: "{{{basePath}}}".to_owned(),
user_agent: {{#httpUserAgent}}Some("{{{.}}}".to_owned()){{/httpUserAgent}}{{^httpUserAgent}}Some("OpenAPI-Generator/{{{version}}}/rust".to_owned()){{/httpUserAgent}}, user_agent: {{#httpUserAgent}}Some("{{{.}}}".to_owned()){{/httpUserAgent}}{{^httpUserAgent}}Some("OpenAPI-Generator/{{{version}}}/rust".to_owned()){{/httpUserAgent}},
client: client, client,
basic_auth: None, basic_auth: None,
oauth_access_token: None, oauth_access_token: None,
api_key: None, api_key: None,

View File

@ -1,14 +1,16 @@
use std::borrow::Cow;
use std::collections::HashMap; use std::collections::HashMap;
use std::pin::Pin;
use super::{configuration, Error};
use futures; use futures;
use futures::{Future, Stream}; use futures::Future;
use futures::future::*;
use hyper; use hyper;
use hyper::header::UserAgent; use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, HeaderValue, USER_AGENT};
use serde; use serde;
use serde_json; use serde_json;
use super::{configuration, Error};
pub(crate) struct ApiKey { pub(crate) struct ApiKey {
pub in_header: bool, pub in_header: bool,
pub in_query: bool, pub in_query: bool,
@ -32,8 +34,11 @@ pub(crate) enum Auth {
Oauth, Oauth,
} }
/// If the authorization type is unspecified then it will be automatically detected based
/// on the configuration. This functionality is useful when the OpenAPI definition does not
/// include an authorization scheme.
pub(crate) struct Request { pub(crate) struct Request {
auth: Auth, auth: Option<Auth>,
method: hyper::Method, method: hyper::Method,
path: String, path: String,
query_params: HashMap<String, String>, query_params: HashMap<String, String>,
@ -48,9 +53,9 @@ pub(crate) struct Request {
impl Request { impl Request {
pub fn new(method: hyper::Method, path: String) -> Self { pub fn new(method: hyper::Method, path: String) -> Self {
Request { Request {
auth: Auth::None, auth: None,
method: method, method,
path: path, path,
query_params: HashMap::new(), query_params: HashMap::new(),
path_params: HashMap::new(), path_params: HashMap::new(),
form_params: HashMap::new(), form_params: HashMap::new(),
@ -91,24 +96,20 @@ impl Request {
} }
pub fn with_auth(mut self, auth: Auth) -> Self { pub fn with_auth(mut self, auth: Auth) -> Self {
self.auth = auth; self.auth = Some(auth);
self self
} }
pub fn execute<'a, C, U>( pub fn execute<'a, C, U>(
self, self,
conf: &configuration::Configuration<C>, conf: &configuration::Configuration<C>,
) -> Box<dyn Future<Item = U, Error = Error<serde_json::Value>> + 'a> ) -> Pin<Box<dyn Future<Output=Result<U, Error>> + 'a>>
where where
C: hyper::client::Connect, C: hyper::client::connect::Connect + Clone + std::marker::Send + Sync,
U: Sized + 'a, U: Sized + std::marker::Send + 'a,
for<'de> U: serde::Deserialize<'de>, for<'de> U: serde::Deserialize<'de>,
{ {
let mut query_string = ::url::form_urlencoded::Serializer::new("".to_owned()); let mut query_string = ::url::form_urlencoded::Serializer::new("".to_owned());
// raw_headers is for headers we don't know the proper type of (e.g. custom api key
// headers); headers is for ones we do know the type of.
let mut raw_headers = HashMap::new();
let mut headers: hyper::header::Headers = hyper::header::Headers::new();
let mut path = self.path; let mut path = self.path;
for (k, v) in self.path_params { for (k, v) in self.path_params {
@ -116,46 +117,10 @@ impl Request {
path = path.replace(&format!("{{{}}}", k), &v); path = path.replace(&format!("{{{}}}", k), &v);
} }
for (k, v) in self.header_params {
raw_headers.insert(k, v);
}
for (key, val) in self.query_params { for (key, val) in self.query_params {
query_string.append_pair(&key, &val); query_string.append_pair(&key, &val);
} }
match self.auth {
Auth::ApiKey(apikey) => {
if let Some(ref key) = conf.api_key {
let val = apikey.key(&key.prefix, &key.key);
if apikey.in_query {
query_string.append_pair(&apikey.param_name, &val);
}
if apikey.in_header {
raw_headers.insert(apikey.param_name, val);
}
}
}
Auth::Basic => {
if let Some(ref auth_conf) = conf.basic_auth {
let auth = hyper::header::Authorization(hyper::header::Basic {
username: auth_conf.0.to_owned(),
password: auth_conf.1.to_owned(),
});
headers.set(auth);
}
}
Auth::Oauth => {
if let Some(ref token) = conf.oauth_access_token {
let auth = hyper::header::Authorization(hyper::header::Bearer {
token: token.to_owned(),
});
headers.set(auth);
}
}
Auth::None => {}
}
let mut uri_str = format!("{}{}", conf.base_path, path); let mut uri_str = format!("{}{}", conf.base_path, path);
let query_string_str = query_string.finish(); let query_string_str = query_string.finish();
@ -164,76 +129,110 @@ impl Request {
uri_str += &query_string_str; uri_str += &query_string_str;
} }
let uri: hyper::Uri = match uri_str.parse() { let uri: hyper::Uri = match uri_str.parse() {
Err(e) => { Err(e) => return Box::pin(futures::future::err(Error::UriError(e))),
return Box::new(futures::future::err(Error::UriError(e)));
}
Ok(u) => u, Ok(u) => u,
}; };
let mut req = hyper::Request::new(self.method, uri); let mut req_builder = hyper::Request::builder()
{ .uri(uri)
let req_headers = req.headers_mut(); .method(self.method);
if let Some(ref user_agent) = conf.user_agent {
req_headers.set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
req_headers.extend(headers.iter()); // Detect the authorization type if it hasn't been set.
let auth = self.auth.unwrap_or_else(||
for (key, val) in raw_headers { if conf.api_key.is_some() {
req_headers.set_raw(key, val); panic!("Cannot automatically set the API key from the configuration, it must be specified in the OpenAPI definition")
} else if conf.oauth_access_token.is_some() {
Auth::Oauth
} else if conf.basic_auth.is_some() {
Auth::Basic
} else {
Auth::None
} }
);
match auth {
Auth::ApiKey(apikey) => {
if let Some(ref key) = conf.api_key {
let val = apikey.key(&key.prefix, &key.key);
if apikey.in_query {
query_string.append_pair(&apikey.param_name, &val);
}
if apikey.in_header {
req_builder = req_builder.header(&apikey.param_name, val);
}
}
}
Auth::Basic => {
if let Some(ref auth_conf) = conf.basic_auth {
let mut text = auth_conf.0.clone();
text.push(':');
if let Some(ref pass) = auth_conf.1 {
text.push_str(&pass[..]);
}
let encoded = base64::encode(&text);
req_builder = req_builder.header(AUTHORIZATION, encoded);
}
}
Auth::Oauth => {
if let Some(ref token) = conf.oauth_access_token {
let text = "Bearer ".to_owned() + token;
req_builder = req_builder.header(AUTHORIZATION, text);
}
}
Auth::None => {}
} }
if self.form_params.len() > 0 { if let Some(ref user_agent) = conf.user_agent {
req.headers_mut().set(hyper::header::ContentType::form_url_encoded()); req_builder = req_builder.header(USER_AGENT, match HeaderValue::from_str(user_agent) {
Ok(header_value) => header_value,
Err(e) => return Box::pin(futures::future::err(super::Error::Header(e)))
});
}
for (k, v) in self.header_params {
req_builder = req_builder.header(&k, v);
}
let req_headers = req_builder.headers_mut().unwrap();
let request_result = if self.form_params.len() > 0 {
req_headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/ x-www-form-urlencoded"));
let mut enc = ::url::form_urlencoded::Serializer::new("".to_owned()); let mut enc = ::url::form_urlencoded::Serializer::new("".to_owned());
for (k, v) in self.form_params { for (k, v) in self.form_params {
enc.append_pair(&k, &v); enc.append_pair(&k, &v);
} }
req.set_body(enc.finish()); req_builder.body(hyper::Body::from(enc.finish()))
} } else if let Some(body) = self.serialized_body {
req_headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
req_headers.insert(CONTENT_LENGTH, body.len().into());
req_builder.body(hyper::Body::from(body))
} else {
req_builder.body(hyper::Body::default())
};
let request = match request_result {
Ok(request) => request,
Err(e) => return Box::pin(futures::future::err(Error::from(e)))
};
if let Some(body) = self.serialized_body { let no_return_type = self.no_return_type;
req.headers_mut().set(hyper::header::ContentType::json()); Box::pin(conf.client
req.headers_mut() .request(request)
.set(hyper::header::ContentLength(body.len() as u64)); .map_err(|e| Error::from(e))
req.set_body(body); .and_then(move |response| {
} let status = response.status();
if !status.is_success() {
let no_ret_type = self.no_return_type; futures::future::err::<U, Error>(Error::from((status, response.into_body()))).boxed()
let res = conf.client } else if no_return_type {
.request(req) // This is a hack; if there's no_ret_type, U is (), but serde_json gives an
.map_err(|e| Error::from(e)) // error when deserializing "" into (), so deserialize 'null' into it
.and_then(|resp| { // instead.
let status = resp.status(); // An alternate option would be to require U: Default, and then return
resp.body() // U::default() here instead since () implements that, but then we'd
.concat2() // need to impl default for all models.
.and_then(move |body| Ok((status, body))) futures::future::ok::<U, Error>(serde_json::from_str("null").expect("serde null value")).boxed()
.map_err(|e| Error::from(e)) } else {
}) hyper::body::to_bytes(response.into_body())
.and_then(|(status, body)| { .map(|bytes| serde_json::from_slice(&bytes.unwrap()))
if status.is_success() { .map_err(|e| Error::from(e)).boxed()
Ok(body) }
} else { }))
Err(Error::from((status, &*body)))
}
});
Box::new(
res
.and_then(move |body| {
let parsed: Result<U, _> = if no_ret_type {
// This is a hack; if there's no_ret_type, U is (), but serde_json gives an
// error when deserializing "" into (), so deserialize 'null' into it
// instead.
// An alternate option would be to require U: Default, and then return
// U::default() here instead since () implements that, but then we'd
// need to impl default for all models.
serde_json::from_str("null")
} else {
serde_json::from_slice(&body)
};
parsed.map_err(|e| Error::from(e))
})
)
} }
} }

View File

@ -9,10 +9,12 @@ serde = "^1.0"
serde_derive = "^1.0" serde_derive = "^1.0"
serde_json = "^1.0" serde_json = "^1.0"
url = "^2.2" url = "^2.2"
hyper = "~0.11" hyper = { version = "~0.14", features = ["full"] }
hyper-tls = "~0.5"
http = "~0.2"
serde_yaml = "0.7" serde_yaml = "0.7"
base64 = "~0.7.0" base64 = "~0.7.0"
futures = "0.1.23" futures = "^0.3"
[dev-dependencies] [dev-dependencies]
tokio-core = "*" tokio-core = "*"

View File

@ -10,7 +10,8 @@ pub struct APIClient {
} }
impl APIClient { impl APIClient {
pub fn new<C: hyper::client::Connect>(configuration: Configuration<C>) -> APIClient { pub fn new<C: hyper::client::connect::Connect>(configuration: Configuration<C>) -> APIClient
where C: Clone + std::marker::Send + Sync + 'static {
let rc = Rc::new(configuration); let rc = Rc::new(configuration);
APIClient { APIClient {

View File

@ -10,7 +10,8 @@
use hyper; use hyper;
pub struct Configuration<C: hyper::client::Connect> { pub struct Configuration<C: hyper::client::connect::Connect>
where C: Clone + std::marker::Send + Sync + 'static {
pub base_path: String, pub base_path: String,
pub user_agent: Option<String>, pub user_agent: Option<String>,
pub client: hyper::client::Client<C>, pub client: hyper::client::Client<C>,
@ -27,12 +28,13 @@ pub struct ApiKey {
pub key: String, pub key: String,
} }
impl<C: hyper::client::Connect> Configuration<C> { impl<C: hyper::client::connect::Connect> Configuration<C>
where C: Clone + std::marker::Send + Sync {
pub fn new(client: hyper::client::Client<C>) -> Configuration<C> { pub fn new(client: hyper::client::Client<C>) -> Configuration<C> {
Configuration { Configuration {
base_path: "http://petstore.swagger.io/v2".to_owned(), base_path: "http://petstore.swagger.io/v2".to_owned(),
user_agent: Some("OpenAPI-Generator/1.0.0/rust".to_owned()), user_agent: Some("OpenAPI-Generator/1.0.0/rust".to_owned()),
client: client, client,
basic_auth: None, basic_auth: None,
oauth_access_token: None, oauth_access_token: None,
api_key: None, api_key: None,

View File

@ -1,49 +1,45 @@
use http;
use hyper; use hyper;
use serde;
use serde_json; use serde_json;
#[derive(Debug)] #[derive(Debug)]
pub enum Error<T> { pub enum Error {
UriError(hyper::error::UriError), Api(ApiError),
Header(hyper::http::header::InvalidHeaderValue),
Http(http::Error),
Hyper(hyper::Error), Hyper(hyper::Error),
Serde(serde_json::Error), Serde(serde_json::Error),
ApiError(ApiError<T>), UriError(http::uri::InvalidUri),
} }
#[derive(Debug)] #[derive(Debug)]
pub struct ApiError<T> { pub struct ApiError {
pub code: hyper::StatusCode, pub code: hyper::StatusCode,
pub content: Option<T>, pub body: hyper::body::Body,
} }
impl<'de, T> From<(hyper::StatusCode, &'de [u8])> for Error<T> impl From<(hyper::StatusCode, hyper::body::Body)> for Error {
where T: serde::Deserialize<'de> { fn from(e: (hyper::StatusCode, hyper::body::Body)) -> Self {
fn from(e: (hyper::StatusCode, &'de [u8])) -> Self { Error::Api(ApiError {
if e.1.len() == 0 { code: e.0,
return Error::ApiError(ApiError{ body: e.1,
code: e.0, })
content: None,
});
}
match serde_json::from_slice::<T>(e.1) {
Ok(t) => Error::ApiError(ApiError{
code: e.0,
content: Some(t),
}),
Err(e) => {
Error::from(e)
}
}
} }
} }
impl<T> From<hyper::Error> for Error<T> { impl From<http::Error> for Error {
fn from(e: http::Error) -> Self {
return Error::Http(e)
}
}
impl From<hyper::Error> for Error {
fn from(e: hyper::Error) -> Self { fn from(e: hyper::Error) -> Self {
return Error::Hyper(e) return Error::Hyper(e)
} }
} }
impl<T> From<serde_json::Error> for Error<T> { impl From<serde_json::Error> for Error {
fn from(e: serde_json::Error) -> Self { fn from(e: serde_json::Error) -> Self {
return Error::Serde(e) return Error::Serde(e)
} }

View File

@ -4,27 +4,29 @@
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
* *
* The version of the OpenAPI document: 1.0.0 * The version of the OpenAPI document: 1.0.0
* *
* Generated by: https://openapi-generator.tech * Generated by: https://openapi-generator.tech
*/ */
use std::rc::Rc; use std::rc::Rc;
use std::borrow::Borrow; use std::borrow::Borrow;
use std::pin::Pin;
#[allow(unused_imports)] #[allow(unused_imports)]
use std::option::Option; use std::option::Option;
use hyper; use hyper;
use serde_json;
use futures::Future; use futures::Future;
use super::{Error, configuration}; use super::{Error, configuration};
use super::request as __internal_request; use super::request as __internal_request;
pub struct PetApiClient<C: hyper::client::Connect> { pub struct PetApiClient<C: hyper::client::connect::Connect>
where C: Clone + std::marker::Send + Sync + 'static {
configuration: Rc<configuration::Configuration<C>>, configuration: Rc<configuration::Configuration<C>>,
} }
impl<C: hyper::client::Connect> PetApiClient<C> { impl<C: hyper::client::connect::Connect> PetApiClient<C>
where C: Clone + std::marker::Send + Sync {
pub fn new(configuration: Rc<configuration::Configuration<C>>) -> PetApiClient<C> { pub fn new(configuration: Rc<configuration::Configuration<C>>) -> PetApiClient<C> {
PetApiClient { PetApiClient {
configuration, configuration,
@ -33,19 +35,21 @@ impl<C: hyper::client::Connect> PetApiClient<C> {
} }
pub trait PetApi { pub trait PetApi {
fn add_pet(&self, pet: crate::models::Pet) -> Box<dyn Future<Item = crate::models::Pet, Error = Error<serde_json::Value>>>; fn add_pet(&self, body: crate::models::Pet) -> Pin<Box<dyn Future<Output = Result<(), Error>>>>;
fn delete_pet(&self, pet_id: i64, api_key: Option<&str>) -> Box<dyn Future<Item = (), Error = Error<serde_json::Value>>>; fn delete_pet(&self, pet_id: i64, api_key: Option<&str>) -> Pin<Box<dyn Future<Output = Result<(), Error>>>>;
fn find_pets_by_status(&self, status: Vec<String>) -> Box<dyn Future<Item = Vec<crate::models::Pet>, Error = Error<serde_json::Value>>>; fn find_pets_by_status(&self, status: Vec<String>) -> Pin<Box<dyn Future<Output = Result<Vec<crate::models::Pet>, Error>>>>;
fn find_pets_by_tags(&self, tags: Vec<String>) -> Box<dyn Future<Item = Vec<crate::models::Pet>, Error = Error<serde_json::Value>>>; fn find_pets_by_tags(&self, tags: Vec<String>) -> Pin<Box<dyn Future<Output = Result<Vec<crate::models::Pet>, Error>>>>;
fn get_pet_by_id(&self, pet_id: i64) -> Box<dyn Future<Item = crate::models::Pet, Error = Error<serde_json::Value>>>; fn get_pet_by_id(&self, pet_id: i64) -> Pin<Box<dyn Future<Output = Result<crate::models::Pet, Error>>>>;
fn update_pet(&self, pet: crate::models::Pet) -> Box<dyn Future<Item = crate::models::Pet, Error = Error<serde_json::Value>>>; fn update_pet(&self, body: crate::models::Pet) -> Pin<Box<dyn Future<Output = Result<(), Error>>>>;
fn update_pet_with_form(&self, pet_id: i64, name: Option<&str>, status: Option<&str>) -> Box<dyn Future<Item = (), Error = Error<serde_json::Value>>>; fn update_pet_with_form(&self, pet_id: i64, name: Option<&str>, status: Option<&str>) -> Pin<Box<dyn Future<Output = Result<(), Error>>>>;
fn upload_file(&self, pet_id: i64, additional_metadata: Option<&str>, file: Option<std::path::PathBuf>) -> Box<dyn Future<Item = crate::models::ApiResponse, Error = Error<serde_json::Value>>>; fn upload_file(&self, pet_id: i64, additional_metadata: Option<&str>, file: Option<std::path::PathBuf>) -> Pin<Box<dyn Future<Output = Result<crate::models::ApiResponse, Error>>>>;
} }
impl<C: hyper::client::Connect>PetApi for PetApiClient<C> { impl<C: hyper::client::connect::Connect>PetApi for PetApiClient<C>
fn add_pet(&self, pet: crate::models::Pet) -> Box<dyn Future<Item = crate::models::Pet, Error = Error<serde_json::Value>>> { where C: Clone + std::marker::Send + Sync {
let mut req = __internal_request::Request::new(hyper::Method::Post, "/pet".to_string()) #[allow(unused_mut)]
fn add_pet(&self, body: crate::models::Pet) -> Pin<Box<dyn Future<Output = Result<(), Error>>>> {
let mut req = __internal_request::Request::new(hyper::Method::POST, "/pet".to_string())
.with_auth(__internal_request::Auth::Oauth) .with_auth(__internal_request::Auth::Oauth)
; ;
req = req.with_body_param(pet); req = req.with_body_param(pet);
@ -53,8 +57,9 @@ impl<C: hyper::client::Connect>PetApi for PetApiClient<C> {
req.execute(self.configuration.borrow()) req.execute(self.configuration.borrow())
} }
fn delete_pet(&self, pet_id: i64, api_key: Option<&str>) -> Box<dyn Future<Item = (), Error = Error<serde_json::Value>>> { #[allow(unused_mut)]
let mut req = __internal_request::Request::new(hyper::Method::Delete, "/pet/{petId}".to_string()) fn delete_pet(&self, pet_id: i64, api_key: Option<&str>) -> Pin<Box<dyn Future<Output = Result<(), Error>>>> {
let mut req = __internal_request::Request::new(hyper::Method::DELETE, "/pet/{petId}".to_string())
.with_auth(__internal_request::Auth::Oauth) .with_auth(__internal_request::Auth::Oauth)
; ;
req = req.with_path_param("petId".to_string(), pet_id.to_string()); req = req.with_path_param("petId".to_string(), pet_id.to_string());
@ -66,8 +71,9 @@ impl<C: hyper::client::Connect>PetApi for PetApiClient<C> {
req.execute(self.configuration.borrow()) req.execute(self.configuration.borrow())
} }
fn find_pets_by_status(&self, status: Vec<String>) -> Box<dyn Future<Item = Vec<crate::models::Pet>, Error = Error<serde_json::Value>>> { #[allow(unused_mut)]
let mut req = __internal_request::Request::new(hyper::Method::Get, "/pet/findByStatus".to_string()) fn find_pets_by_status(&self, status: Vec<String>) -> Pin<Box<dyn Future<Output = Result<Vec<crate::models::Pet>, Error>>>> {
let mut req = __internal_request::Request::new(hyper::Method::GET, "/pet/findByStatus".to_string())
.with_auth(__internal_request::Auth::Oauth) .with_auth(__internal_request::Auth::Oauth)
; ;
req = req.with_query_param("status".to_string(), status.join(",").to_string()); req = req.with_query_param("status".to_string(), status.join(",").to_string());
@ -75,8 +81,9 @@ impl<C: hyper::client::Connect>PetApi for PetApiClient<C> {
req.execute(self.configuration.borrow()) req.execute(self.configuration.borrow())
} }
fn find_pets_by_tags(&self, tags: Vec<String>) -> Box<dyn Future<Item = Vec<crate::models::Pet>, Error = Error<serde_json::Value>>> { #[allow(unused_mut)]
let mut req = __internal_request::Request::new(hyper::Method::Get, "/pet/findByTags".to_string()) fn find_pets_by_tags(&self, tags: Vec<String>) -> Pin<Box<dyn Future<Output = Result<Vec<crate::models::Pet>, Error>>>> {
let mut req = __internal_request::Request::new(hyper::Method::GET, "/pet/findByTags".to_string())
.with_auth(__internal_request::Auth::Oauth) .with_auth(__internal_request::Auth::Oauth)
; ;
req = req.with_query_param("tags".to_string(), tags.join(",").to_string()); req = req.with_query_param("tags".to_string(), tags.join(",").to_string());
@ -84,8 +91,9 @@ impl<C: hyper::client::Connect>PetApi for PetApiClient<C> {
req.execute(self.configuration.borrow()) req.execute(self.configuration.borrow())
} }
fn get_pet_by_id(&self, pet_id: i64) -> Box<dyn Future<Item = crate::models::Pet, Error = Error<serde_json::Value>>> { #[allow(unused_mut)]
let mut req = __internal_request::Request::new(hyper::Method::Get, "/pet/{petId}".to_string()) fn get_pet_by_id(&self, pet_id: i64) -> Pin<Box<dyn Future<Output = Result<crate::models::Pet, Error>>>> {
let mut req = __internal_request::Request::new(hyper::Method::GET, "/pet/{petId}".to_string())
.with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{ .with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{
in_header: true, in_header: true,
in_query: false, in_query: false,
@ -97,8 +105,9 @@ impl<C: hyper::client::Connect>PetApi for PetApiClient<C> {
req.execute(self.configuration.borrow()) req.execute(self.configuration.borrow())
} }
fn update_pet(&self, pet: crate::models::Pet) -> Box<dyn Future<Item = crate::models::Pet, Error = Error<serde_json::Value>>> { #[allow(unused_mut)]
let mut req = __internal_request::Request::new(hyper::Method::Put, "/pet".to_string()) fn update_pet(&self, body: crate::models::Pet) -> Pin<Box<dyn Future<Output = Result<(), Error>>>> {
let mut req = __internal_request::Request::new(hyper::Method::PUT, "/pet".to_string())
.with_auth(__internal_request::Auth::Oauth) .with_auth(__internal_request::Auth::Oauth)
; ;
req = req.with_body_param(pet); req = req.with_body_param(pet);
@ -106,8 +115,9 @@ impl<C: hyper::client::Connect>PetApi for PetApiClient<C> {
req.execute(self.configuration.borrow()) req.execute(self.configuration.borrow())
} }
fn update_pet_with_form(&self, pet_id: i64, name: Option<&str>, status: Option<&str>) -> Box<dyn Future<Item = (), Error = Error<serde_json::Value>>> { #[allow(unused_mut)]
let mut req = __internal_request::Request::new(hyper::Method::Post, "/pet/{petId}".to_string()) fn update_pet_with_form(&self, pet_id: i64, name: Option<&str>, status: Option<&str>) -> Pin<Box<dyn Future<Output = Result<(), Error>>>> {
let mut req = __internal_request::Request::new(hyper::Method::POST, "/pet/{petId}".to_string())
.with_auth(__internal_request::Auth::Oauth) .with_auth(__internal_request::Auth::Oauth)
; ;
req = req.with_path_param("petId".to_string(), pet_id.to_string()); req = req.with_path_param("petId".to_string(), pet_id.to_string());
@ -122,8 +132,9 @@ impl<C: hyper::client::Connect>PetApi for PetApiClient<C> {
req.execute(self.configuration.borrow()) req.execute(self.configuration.borrow())
} }
fn upload_file(&self, pet_id: i64, additional_metadata: Option<&str>, file: Option<std::path::PathBuf>) -> Box<dyn Future<Item = crate::models::ApiResponse, Error = Error<serde_json::Value>>> { #[allow(unused_mut)]
let mut req = __internal_request::Request::new(hyper::Method::Post, "/pet/{petId}/uploadImage".to_string()) fn upload_file(&self, pet_id: i64, additional_metadata: Option<&str>, file: Option<std::path::PathBuf>) -> Pin<Box<dyn Future<Output = Result<crate::models::ApiResponse, Error>>>> {
let mut req = __internal_request::Request::new(hyper::Method::POST, "/pet/{petId}/uploadImage".to_string())
.with_auth(__internal_request::Auth::Oauth) .with_auth(__internal_request::Auth::Oauth)
; ;
req = req.with_path_param("petId".to_string(), pet_id.to_string()); req = req.with_path_param("petId".to_string(), pet_id.to_string());

View File

@ -1,14 +1,16 @@
use std::borrow::Cow;
use std::collections::HashMap; use std::collections::HashMap;
use std::pin::Pin;
use super::{configuration, Error};
use futures; use futures;
use futures::{Future, Stream}; use futures::Future;
use futures::future::*;
use hyper; use hyper;
use hyper::header::UserAgent; use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, HeaderValue, USER_AGENT};
use serde; use serde;
use serde_json; use serde_json;
use super::{configuration, Error};
pub(crate) struct ApiKey { pub(crate) struct ApiKey {
pub in_header: bool, pub in_header: bool,
pub in_query: bool, pub in_query: bool,
@ -32,8 +34,11 @@ pub(crate) enum Auth {
Oauth, Oauth,
} }
/// If the authorization type is unspecified then it will be automatically detected based
/// on the configuration. This functionality is useful when the OpenAPI definition does not
/// include an authorization scheme.
pub(crate) struct Request { pub(crate) struct Request {
auth: Auth, auth: Option<Auth>,
method: hyper::Method, method: hyper::Method,
path: String, path: String,
query_params: HashMap<String, String>, query_params: HashMap<String, String>,
@ -48,9 +53,9 @@ pub(crate) struct Request {
impl Request { impl Request {
pub fn new(method: hyper::Method, path: String) -> Self { pub fn new(method: hyper::Method, path: String) -> Self {
Request { Request {
auth: Auth::None, auth: None,
method: method, method,
path: path, path,
query_params: HashMap::new(), query_params: HashMap::new(),
path_params: HashMap::new(), path_params: HashMap::new(),
form_params: HashMap::new(), form_params: HashMap::new(),
@ -91,24 +96,20 @@ impl Request {
} }
pub fn with_auth(mut self, auth: Auth) -> Self { pub fn with_auth(mut self, auth: Auth) -> Self {
self.auth = auth; self.auth = Some(auth);
self self
} }
pub fn execute<'a, C, U>( pub fn execute<'a, C, U>(
self, self,
conf: &configuration::Configuration<C>, conf: &configuration::Configuration<C>,
) -> Box<dyn Future<Item = U, Error = Error<serde_json::Value>> + 'a> ) -> Pin<Box<dyn Future<Output=Result<U, Error>> + 'a>>
where where
C: hyper::client::Connect, C: hyper::client::connect::Connect + Clone + std::marker::Send + Sync,
U: Sized + 'a, U: Sized + std::marker::Send + 'a,
for<'de> U: serde::Deserialize<'de>, for<'de> U: serde::Deserialize<'de>,
{ {
let mut query_string = ::url::form_urlencoded::Serializer::new("".to_owned()); let mut query_string = ::url::form_urlencoded::Serializer::new("".to_owned());
// raw_headers is for headers we don't know the proper type of (e.g. custom api key
// headers); headers is for ones we do know the type of.
let mut raw_headers = HashMap::new();
let mut headers: hyper::header::Headers = hyper::header::Headers::new();
let mut path = self.path; let mut path = self.path;
for (k, v) in self.path_params { for (k, v) in self.path_params {
@ -116,46 +117,10 @@ impl Request {
path = path.replace(&format!("{{{}}}", k), &v); path = path.replace(&format!("{{{}}}", k), &v);
} }
for (k, v) in self.header_params {
raw_headers.insert(k, v);
}
for (key, val) in self.query_params { for (key, val) in self.query_params {
query_string.append_pair(&key, &val); query_string.append_pair(&key, &val);
} }
match self.auth {
Auth::ApiKey(apikey) => {
if let Some(ref key) = conf.api_key {
let val = apikey.key(&key.prefix, &key.key);
if apikey.in_query {
query_string.append_pair(&apikey.param_name, &val);
}
if apikey.in_header {
raw_headers.insert(apikey.param_name, val);
}
}
}
Auth::Basic => {
if let Some(ref auth_conf) = conf.basic_auth {
let auth = hyper::header::Authorization(hyper::header::Basic {
username: auth_conf.0.to_owned(),
password: auth_conf.1.to_owned(),
});
headers.set(auth);
}
}
Auth::Oauth => {
if let Some(ref token) = conf.oauth_access_token {
let auth = hyper::header::Authorization(hyper::header::Bearer {
token: token.to_owned(),
});
headers.set(auth);
}
}
Auth::None => {}
}
let mut uri_str = format!("{}{}", conf.base_path, path); let mut uri_str = format!("{}{}", conf.base_path, path);
let query_string_str = query_string.finish(); let query_string_str = query_string.finish();
@ -164,76 +129,110 @@ impl Request {
uri_str += &query_string_str; uri_str += &query_string_str;
} }
let uri: hyper::Uri = match uri_str.parse() { let uri: hyper::Uri = match uri_str.parse() {
Err(e) => { Err(e) => return Box::pin(futures::future::err(Error::UriError(e))),
return Box::new(futures::future::err(Error::UriError(e)));
}
Ok(u) => u, Ok(u) => u,
}; };
let mut req = hyper::Request::new(self.method, uri); let mut req_builder = hyper::Request::builder()
{ .uri(uri)
let req_headers = req.headers_mut(); .method(self.method);
if let Some(ref user_agent) = conf.user_agent {
req_headers.set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
req_headers.extend(headers.iter()); // Detect the authorization type if it hasn't been set.
let auth = self.auth.unwrap_or_else(||
for (key, val) in raw_headers { if conf.api_key.is_some() {
req_headers.set_raw(key, val); panic!("Cannot automatically set the API key from the configuration, it must be specified in the OpenAPI definition")
} else if conf.oauth_access_token.is_some() {
Auth::Oauth
} else if conf.basic_auth.is_some() {
Auth::Basic
} else {
Auth::None
} }
);
match auth {
Auth::ApiKey(apikey) => {
if let Some(ref key) = conf.api_key {
let val = apikey.key(&key.prefix, &key.key);
if apikey.in_query {
query_string.append_pair(&apikey.param_name, &val);
}
if apikey.in_header {
req_builder = req_builder.header(&apikey.param_name, val);
}
}
}
Auth::Basic => {
if let Some(ref auth_conf) = conf.basic_auth {
let mut text = auth_conf.0.clone();
text.push(':');
if let Some(ref pass) = auth_conf.1 {
text.push_str(&pass[..]);
}
let encoded = base64::encode(&text);
req_builder = req_builder.header(AUTHORIZATION, encoded);
}
}
Auth::Oauth => {
if let Some(ref token) = conf.oauth_access_token {
let text = "Bearer ".to_owned() + token;
req_builder = req_builder.header(AUTHORIZATION, text);
}
}
Auth::None => {}
} }
if self.form_params.len() > 0 { if let Some(ref user_agent) = conf.user_agent {
req.headers_mut().set(hyper::header::ContentType::form_url_encoded()); req_builder = req_builder.header(USER_AGENT, match HeaderValue::from_str(user_agent) {
Ok(header_value) => header_value,
Err(e) => return Box::pin(futures::future::err(super::Error::Header(e)))
});
}
for (k, v) in self.header_params {
req_builder = req_builder.header(&k, v);
}
let req_headers = req_builder.headers_mut().unwrap();
let request_result = if self.form_params.len() > 0 {
req_headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/ x-www-form-urlencoded"));
let mut enc = ::url::form_urlencoded::Serializer::new("".to_owned()); let mut enc = ::url::form_urlencoded::Serializer::new("".to_owned());
for (k, v) in self.form_params { for (k, v) in self.form_params {
enc.append_pair(&k, &v); enc.append_pair(&k, &v);
} }
req.set_body(enc.finish()); req_builder.body(hyper::Body::from(enc.finish()))
} } else if let Some(body) = self.serialized_body {
req_headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
req_headers.insert(CONTENT_LENGTH, body.len().into());
req_builder.body(hyper::Body::from(body))
} else {
req_builder.body(hyper::Body::default())
};
let request = match request_result {
Ok(request) => request,
Err(e) => return Box::pin(futures::future::err(Error::from(e)))
};
if let Some(body) = self.serialized_body { let no_return_type = self.no_return_type;
req.headers_mut().set(hyper::header::ContentType::json()); Box::pin(conf.client
req.headers_mut() .request(request)
.set(hyper::header::ContentLength(body.len() as u64)); .map_err(|e| Error::from(e))
req.set_body(body); .and_then(move |response| {
} let status = response.status();
if !status.is_success() {
let no_ret_type = self.no_return_type; futures::future::err::<U, Error>(Error::from((status, response.into_body()))).boxed()
let res = conf.client } else if no_return_type {
.request(req) // This is a hack; if there's no_ret_type, U is (), but serde_json gives an
.map_err(|e| Error::from(e)) // error when deserializing "" into (), so deserialize 'null' into it
.and_then(|resp| { // instead.
let status = resp.status(); // An alternate option would be to require U: Default, and then return
resp.body() // U::default() here instead since () implements that, but then we'd
.concat2() // need to impl default for all models.
.and_then(move |body| Ok((status, body))) futures::future::ok::<U, Error>(serde_json::from_str("null").expect("serde null value")).boxed()
.map_err(|e| Error::from(e)) } else {
}) hyper::body::to_bytes(response.into_body())
.and_then(|(status, body)| { .map(|bytes| serde_json::from_slice(&bytes.unwrap()))
if status.is_success() { .map_err(|e| Error::from(e)).boxed()
Ok(body) }
} else { }))
Err(Error::from((status, &*body)))
}
});
Box::new(
res
.and_then(move |body| {
let parsed: Result<U, _> = if no_ret_type {
// This is a hack; if there's no_ret_type, U is (), but serde_json gives an
// error when deserializing "" into (), so deserialize 'null' into it
// instead.
// An alternate option would be to require U: Default, and then return
// U::default() here instead since () implements that, but then we'd
// need to impl default for all models.
serde_json::from_str("null")
} else {
serde_json::from_slice(&body)
};
parsed.map_err(|e| Error::from(e))
})
)
} }
} }

View File

@ -4,27 +4,29 @@
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
* *
* The version of the OpenAPI document: 1.0.0 * The version of the OpenAPI document: 1.0.0
* *
* Generated by: https://openapi-generator.tech * Generated by: https://openapi-generator.tech
*/ */
use std::rc::Rc; use std::rc::Rc;
use std::borrow::Borrow; use std::borrow::Borrow;
use std::pin::Pin;
#[allow(unused_imports)] #[allow(unused_imports)]
use std::option::Option; use std::option::Option;
use hyper; use hyper;
use serde_json;
use futures::Future; use futures::Future;
use super::{Error, configuration}; use super::{Error, configuration};
use super::request as __internal_request; use super::request as __internal_request;
pub struct StoreApiClient<C: hyper::client::Connect> { pub struct StoreApiClient<C: hyper::client::connect::Connect>
where C: Clone + std::marker::Send + Sync + 'static {
configuration: Rc<configuration::Configuration<C>>, configuration: Rc<configuration::Configuration<C>>,
} }
impl<C: hyper::client::Connect> StoreApiClient<C> { impl<C: hyper::client::connect::Connect> StoreApiClient<C>
where C: Clone + std::marker::Send + Sync {
pub fn new(configuration: Rc<configuration::Configuration<C>>) -> StoreApiClient<C> { pub fn new(configuration: Rc<configuration::Configuration<C>>) -> StoreApiClient<C> {
StoreApiClient { StoreApiClient {
configuration, configuration,
@ -33,15 +35,17 @@ impl<C: hyper::client::Connect> StoreApiClient<C> {
} }
pub trait StoreApi { pub trait StoreApi {
fn delete_order(&self, order_id: &str) -> Box<dyn Future<Item = (), Error = Error<serde_json::Value>>>; fn delete_order(&self, order_id: &str) -> Pin<Box<dyn Future<Output = Result<(), Error>>>>;
fn get_inventory(&self, ) -> Box<dyn Future<Item = ::std::collections::HashMap<String, i32>, Error = Error<serde_json::Value>>>; fn get_inventory(&self, ) -> Pin<Box<dyn Future<Output = Result<::std::collections::HashMap<String, i32>, Error>>>>;
fn get_order_by_id(&self, order_id: i64) -> Box<dyn Future<Item = crate::models::Order, Error = Error<serde_json::Value>>>; fn get_order_by_id(&self, order_id: i64) -> Pin<Box<dyn Future<Output = Result<crate::models::Order, Error>>>>;
fn place_order(&self, order: crate::models::Order) -> Box<dyn Future<Item = crate::models::Order, Error = Error<serde_json::Value>>>; fn place_order(&self, body: crate::models::Order) -> Pin<Box<dyn Future<Output = Result<crate::models::Order, Error>>>>;
} }
impl<C: hyper::client::Connect>StoreApi for StoreApiClient<C> { impl<C: hyper::client::connect::Connect>StoreApi for StoreApiClient<C>
fn delete_order(&self, order_id: &str) -> Box<dyn Future<Item = (), Error = Error<serde_json::Value>>> { where C: Clone + std::marker::Send + Sync {
let mut req = __internal_request::Request::new(hyper::Method::Delete, "/store/order/{orderId}".to_string()) #[allow(unused_mut)]
fn delete_order(&self, order_id: &str) -> Pin<Box<dyn Future<Output = Result<(), Error>>>> {
let mut req = __internal_request::Request::new(hyper::Method::DELETE, "/store/order/{orderId}".to_string())
; ;
req = req.with_path_param("orderId".to_string(), order_id.to_string()); req = req.with_path_param("orderId".to_string(), order_id.to_string());
req = req.returns_nothing(); req = req.returns_nothing();
@ -49,8 +53,9 @@ impl<C: hyper::client::Connect>StoreApi for StoreApiClient<C> {
req.execute(self.configuration.borrow()) req.execute(self.configuration.borrow())
} }
fn get_inventory(&self, ) -> Box<dyn Future<Item = ::std::collections::HashMap<String, i32>, Error = Error<serde_json::Value>>> { #[allow(unused_mut)]
let mut req = __internal_request::Request::new(hyper::Method::Get, "/store/inventory".to_string()) fn get_inventory(&self, ) -> Pin<Box<dyn Future<Output = Result<::std::collections::HashMap<String, i32>, Error>>>> {
let mut req = __internal_request::Request::new(hyper::Method::GET, "/store/inventory".to_string())
.with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{ .with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{
in_header: true, in_header: true,
in_query: false, in_query: false,
@ -61,16 +66,18 @@ impl<C: hyper::client::Connect>StoreApi for StoreApiClient<C> {
req.execute(self.configuration.borrow()) req.execute(self.configuration.borrow())
} }
fn get_order_by_id(&self, order_id: i64) -> Box<dyn Future<Item = crate::models::Order, Error = Error<serde_json::Value>>> { #[allow(unused_mut)]
let mut req = __internal_request::Request::new(hyper::Method::Get, "/store/order/{orderId}".to_string()) fn get_order_by_id(&self, order_id: i64) -> Pin<Box<dyn Future<Output = Result<crate::models::Order, Error>>>> {
let mut req = __internal_request::Request::new(hyper::Method::GET, "/store/order/{orderId}".to_string())
; ;
req = req.with_path_param("orderId".to_string(), order_id.to_string()); req = req.with_path_param("orderId".to_string(), order_id.to_string());
req.execute(self.configuration.borrow()) req.execute(self.configuration.borrow())
} }
fn place_order(&self, order: crate::models::Order) -> Box<dyn Future<Item = crate::models::Order, Error = Error<serde_json::Value>>> { #[allow(unused_mut)]
let mut req = __internal_request::Request::new(hyper::Method::Post, "/store/order".to_string()) fn place_order(&self, body: crate::models::Order) -> Pin<Box<dyn Future<Output = Result<crate::models::Order, Error>>>> {
let mut req = __internal_request::Request::new(hyper::Method::POST, "/store/order".to_string())
; ;
req = req.with_body_param(order); req = req.with_body_param(order);

View File

@ -4,27 +4,29 @@
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
* *
* The version of the OpenAPI document: 1.0.0 * The version of the OpenAPI document: 1.0.0
* *
* Generated by: https://openapi-generator.tech * Generated by: https://openapi-generator.tech
*/ */
use std::rc::Rc; use std::rc::Rc;
use std::borrow::Borrow; use std::borrow::Borrow;
use std::pin::Pin;
#[allow(unused_imports)] #[allow(unused_imports)]
use std::option::Option; use std::option::Option;
use hyper; use hyper;
use serde_json;
use futures::Future; use futures::Future;
use super::{Error, configuration}; use super::{Error, configuration};
use super::request as __internal_request; use super::request as __internal_request;
pub struct UserApiClient<C: hyper::client::Connect> { pub struct UserApiClient<C: hyper::client::connect::Connect>
where C: Clone + std::marker::Send + Sync + 'static {
configuration: Rc<configuration::Configuration<C>>, configuration: Rc<configuration::Configuration<C>>,
} }
impl<C: hyper::client::Connect> UserApiClient<C> { impl<C: hyper::client::connect::Connect> UserApiClient<C>
where C: Clone + std::marker::Send + Sync {
pub fn new(configuration: Rc<configuration::Configuration<C>>) -> UserApiClient<C> { pub fn new(configuration: Rc<configuration::Configuration<C>>) -> UserApiClient<C> {
UserApiClient { UserApiClient {
configuration, configuration,
@ -33,24 +35,21 @@ impl<C: hyper::client::Connect> UserApiClient<C> {
} }
pub trait UserApi { pub trait UserApi {
fn create_user(&self, user: crate::models::User) -> Box<dyn Future<Item = (), Error = Error<serde_json::Value>>>; fn create_user(&self, body: crate::models::User) -> Pin<Box<dyn Future<Output = Result<(), Error>>>>;
fn create_users_with_array_input(&self, user: Vec<crate::models::User>) -> Box<dyn Future<Item = (), Error = Error<serde_json::Value>>>; fn create_users_with_array_input(&self, body: Vec<crate::models::User>) -> Pin<Box<dyn Future<Output = Result<(), Error>>>>;
fn create_users_with_list_input(&self, user: Vec<crate::models::User>) -> Box<dyn Future<Item = (), Error = Error<serde_json::Value>>>; fn create_users_with_list_input(&self, body: Vec<crate::models::User>) -> Pin<Box<dyn Future<Output = Result<(), Error>>>>;
fn delete_user(&self, username: &str) -> Box<dyn Future<Item = (), Error = Error<serde_json::Value>>>; fn delete_user(&self, username: &str) -> Pin<Box<dyn Future<Output = Result<(), Error>>>>;
fn get_user_by_name(&self, username: &str) -> Box<dyn Future<Item = crate::models::User, Error = Error<serde_json::Value>>>; fn get_user_by_name(&self, username: &str) -> Pin<Box<dyn Future<Output = Result<crate::models::User, Error>>>>;
fn login_user(&self, username: &str, password: &str) -> Box<dyn Future<Item = String, Error = Error<serde_json::Value>>>; fn login_user(&self, username: &str, password: &str) -> Pin<Box<dyn Future<Output = Result<String, Error>>>>;
fn logout_user(&self, ) -> Box<dyn Future<Item = (), Error = Error<serde_json::Value>>>; fn logout_user(&self, ) -> Pin<Box<dyn Future<Output = Result<(), Error>>>>;
fn update_user(&self, username: &str, user: crate::models::User) -> Box<dyn Future<Item = (), Error = Error<serde_json::Value>>>; fn update_user(&self, username: &str, body: crate::models::User) -> Pin<Box<dyn Future<Output = Result<(), Error>>>>;
} }
impl<C: hyper::client::Connect>UserApi for UserApiClient<C> { impl<C: hyper::client::connect::Connect>UserApi for UserApiClient<C>
fn create_user(&self, user: crate::models::User) -> Box<dyn Future<Item = (), Error = Error<serde_json::Value>>> { where C: Clone + std::marker::Send + Sync {
let mut req = __internal_request::Request::new(hyper::Method::Post, "/user".to_string()) #[allow(unused_mut)]
.with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{ fn create_user(&self, body: crate::models::User) -> Pin<Box<dyn Future<Output = Result<(), Error>>>> {
in_header: true, let mut req = __internal_request::Request::new(hyper::Method::POST, "/user".to_string())
in_query: false,
param_name: "api_key".to_owned(),
}))
; ;
req = req.with_body_param(user); req = req.with_body_param(user);
req = req.returns_nothing(); req = req.returns_nothing();
@ -58,13 +57,9 @@ impl<C: hyper::client::Connect>UserApi for UserApiClient<C> {
req.execute(self.configuration.borrow()) req.execute(self.configuration.borrow())
} }
fn create_users_with_array_input(&self, user: Vec<crate::models::User>) -> Box<dyn Future<Item = (), Error = Error<serde_json::Value>>> { #[allow(unused_mut)]
let mut req = __internal_request::Request::new(hyper::Method::Post, "/user/createWithArray".to_string()) fn create_users_with_array_input(&self, body: Vec<crate::models::User>) -> Pin<Box<dyn Future<Output = Result<(), Error>>>> {
.with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{ let mut req = __internal_request::Request::new(hyper::Method::POST, "/user/createWithArray".to_string())
in_header: true,
in_query: false,
param_name: "api_key".to_owned(),
}))
; ;
req = req.with_body_param(user); req = req.with_body_param(user);
req = req.returns_nothing(); req = req.returns_nothing();
@ -72,13 +67,9 @@ impl<C: hyper::client::Connect>UserApi for UserApiClient<C> {
req.execute(self.configuration.borrow()) req.execute(self.configuration.borrow())
} }
fn create_users_with_list_input(&self, user: Vec<crate::models::User>) -> Box<dyn Future<Item = (), Error = Error<serde_json::Value>>> { #[allow(unused_mut)]
let mut req = __internal_request::Request::new(hyper::Method::Post, "/user/createWithList".to_string()) fn create_users_with_list_input(&self, body: Vec<crate::models::User>) -> Pin<Box<dyn Future<Output = Result<(), Error>>>> {
.with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{ let mut req = __internal_request::Request::new(hyper::Method::POST, "/user/createWithList".to_string())
in_header: true,
in_query: false,
param_name: "api_key".to_owned(),
}))
; ;
req = req.with_body_param(user); req = req.with_body_param(user);
req = req.returns_nothing(); req = req.returns_nothing();
@ -86,13 +77,9 @@ impl<C: hyper::client::Connect>UserApi for UserApiClient<C> {
req.execute(self.configuration.borrow()) req.execute(self.configuration.borrow())
} }
fn delete_user(&self, username: &str) -> Box<dyn Future<Item = (), Error = Error<serde_json::Value>>> { #[allow(unused_mut)]
let mut req = __internal_request::Request::new(hyper::Method::Delete, "/user/{username}".to_string()) fn delete_user(&self, username: &str) -> Pin<Box<dyn Future<Output = Result<(), Error>>>> {
.with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{ let mut req = __internal_request::Request::new(hyper::Method::DELETE, "/user/{username}".to_string())
in_header: true,
in_query: false,
param_name: "api_key".to_owned(),
}))
; ;
req = req.with_path_param("username".to_string(), username.to_string()); req = req.with_path_param("username".to_string(), username.to_string());
req = req.returns_nothing(); req = req.returns_nothing();
@ -100,16 +87,18 @@ impl<C: hyper::client::Connect>UserApi for UserApiClient<C> {
req.execute(self.configuration.borrow()) req.execute(self.configuration.borrow())
} }
fn get_user_by_name(&self, username: &str) -> Box<dyn Future<Item = crate::models::User, Error = Error<serde_json::Value>>> { #[allow(unused_mut)]
let mut req = __internal_request::Request::new(hyper::Method::Get, "/user/{username}".to_string()) fn get_user_by_name(&self, username: &str) -> Pin<Box<dyn Future<Output = Result<crate::models::User, Error>>>> {
let mut req = __internal_request::Request::new(hyper::Method::GET, "/user/{username}".to_string())
; ;
req = req.with_path_param("username".to_string(), username.to_string()); req = req.with_path_param("username".to_string(), username.to_string());
req.execute(self.configuration.borrow()) req.execute(self.configuration.borrow())
} }
fn login_user(&self, username: &str, password: &str) -> Box<dyn Future<Item = String, Error = Error<serde_json::Value>>> { #[allow(unused_mut)]
let mut req = __internal_request::Request::new(hyper::Method::Get, "/user/login".to_string()) fn login_user(&self, username: &str, password: &str) -> Pin<Box<dyn Future<Output = Result<String, Error>>>> {
let mut req = __internal_request::Request::new(hyper::Method::GET, "/user/login".to_string())
; ;
req = req.with_query_param("username".to_string(), username.to_string()); req = req.with_query_param("username".to_string(), username.to_string());
req = req.with_query_param("password".to_string(), password.to_string()); req = req.with_query_param("password".to_string(), password.to_string());
@ -117,26 +106,18 @@ impl<C: hyper::client::Connect>UserApi for UserApiClient<C> {
req.execute(self.configuration.borrow()) req.execute(self.configuration.borrow())
} }
fn logout_user(&self, ) -> Box<dyn Future<Item = (), Error = Error<serde_json::Value>>> { #[allow(unused_mut)]
let mut req = __internal_request::Request::new(hyper::Method::Get, "/user/logout".to_string()) fn logout_user(&self, ) -> Pin<Box<dyn Future<Output = Result<(), Error>>>> {
.with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{ let mut req = __internal_request::Request::new(hyper::Method::GET, "/user/logout".to_string())
in_header: true,
in_query: false,
param_name: "api_key".to_owned(),
}))
; ;
req = req.returns_nothing(); req = req.returns_nothing();
req.execute(self.configuration.borrow()) req.execute(self.configuration.borrow())
} }
fn update_user(&self, username: &str, user: crate::models::User) -> Box<dyn Future<Item = (), Error = Error<serde_json::Value>>> { #[allow(unused_mut)]
let mut req = __internal_request::Request::new(hyper::Method::Put, "/user/{username}".to_string()) fn update_user(&self, username: &str, body: crate::models::User) -> Pin<Box<dyn Future<Output = Result<(), Error>>>> {
.with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{ let mut req = __internal_request::Request::new(hyper::Method::PUT, "/user/{username}".to_string())
in_header: true,
in_query: false,
param_name: "api_key".to_owned(),
}))
; ;
req = req.with_path_param("username".to_string(), username.to_string()); req = req.with_path_param("username".to_string(), username.to_string());
req = req.with_body_param(user); req = req.with_body_param(user);