[Rust] Split out request logic, implement form parameters (#528)

* [Rust] Move request logic into standalone file

This reduces the number of variables which are used in the generated
operations, thus fixing #512.

This also fixed a TODO related to URI parsing errors.
Other than that, it is meant to be functionally identical.

* [Rust] Add support for non-file form params

Up until now, they just weren't there at all

* [Rust] Use more rustic terms in example
This commit is contained in:
Euan Kemp 2018-07-23 08:10:53 -07:00 committed by William Cheng
parent a9961a062a
commit 2e6bec7345
12 changed files with 637 additions and 1239 deletions

View File

@ -165,8 +165,9 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("configuration.mustache", apiFolder, "configuration.rs")); supportingFiles.add(new SupportingFile("configuration.mustache", apiFolder, "configuration.rs"));
supportingFiles.add(new SupportingFile(".travis.yml", "", ".travis.yml")); supportingFiles.add(new SupportingFile(".travis.yml", "", ".travis.yml"));
supportingFiles.add(new SupportingFile("client.mustache", apiFolder, "client.rs"));
supportingFiles.add(new SupportingFile("api_mod.mustache", apiFolder, "mod.rs")); supportingFiles.add(new SupportingFile("api_mod.mustache", apiFolder, "mod.rs"));
supportingFiles.add(new SupportingFile("client.mustache", apiFolder, "client.rs"));
supportingFiles.add(new SupportingFile("request.rs", apiFolder, "request.rs"));
supportingFiles.add(new SupportingFile("model_mod.mustache", modelFolder, "mod.rs")); supportingFiles.add(new SupportingFile("model_mod.mustache", modelFolder, "mod.rs"));
supportingFiles.add(new SupportingFile("lib.rs", "src", "lib.rs")); supportingFiles.add(new SupportingFile("lib.rs", "src", "lib.rs"));
supportingFiles.add(new SupportingFile("Cargo.mustache", "", "Cargo.toml")); supportingFiles.add(new SupportingFile("Cargo.mustache", "", "Cargo.toml"));

View File

@ -1,17 +1,13 @@
{{>partial_header}} {{>partial_header}}
use std::rc::Rc; use std::rc::Rc;
use std::borrow::Borrow; use std::borrow::Borrow;
use std::borrow::Cow;
use std::collections::HashMap;
use hyper; use hyper;
use serde_json; use serde_json;
use futures; use futures::Future;
use futures::{Future, Stream};
use hyper::header::UserAgent;
use super::{Error, configuration}; use super::{Error, configuration};
use super::request as __internal_request;
pub struct {{{classname}}}Client<C: hyper::client::Connect> { pub struct {{{classname}}}Client<C: hyper::client::Connect> {
configuration: Rc<configuration::Configuration<C>>, configuration: Rc<configuration::Configuration<C>>,
@ -38,129 +34,54 @@ impl<C: hyper::client::Connect>{{classname}} for {{classname}}Client<C> {
{{#operations}} {{#operations}}
{{#operation}} {{#operation}}
fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box<Future<Item = {{^returnType}}(){{/returnType}}{{#returnType}}{{{.}}}{{/returnType}}, Error = Error<serde_json::Value>>> { fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box<Future<Item = {{^returnType}}(){{/returnType}}{{#returnType}}{{{.}}}{{/returnType}}, Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow(); __internal_request::Request::new(hyper::Method::{{httpMethod}}, "{{{path}}}".to_string())
{{#hasAuthMethods}}
let mut auth_headers = HashMap::<String, String>::new();
let mut auth_query = HashMap::<String, String>::new();
{{#authMethods}}
{{#isApiKey}}
if let Some(ref apikey) = configuration.api_key {
let key = apikey.key.clone();
let val = match apikey.prefix {
Some(ref prefix) => format!("{} {}", prefix, key),
None => key,
};
{{#isKeyInHeader}}
auth_headers.insert("{{keyParamName}}".to_owned(), val);
{{/isKeyInHeader}}
{{#isKeyInQuery}}
auth_query.insert("{{keyParamName}}".to_owned(), val);
{{/isKeyInQuery}}
};
{{/isApiKey}}
{{#isBasic}}
if let Some(ref auth_conf) = configuration.basic_auth {
let auth = hyper::header::Authorization(
hyper::header::Basic {
username: auth_conf.0.to_owned(),
password: auth_conf.1.to_owned(),
}
);
auth_headers.insert("Authorization".to_owned(), auth.to_string());
};
{{/isBasic}}
{{#isOAuth}}
if let Some(ref token) = configuration.oauth_access_token {
let auth = hyper::header::Authorization(
hyper::header::Bearer {
token: token.to_owned(),
}
);
auth_headers.insert("Authorization".to_owned(), auth.to_string());
};
{{/isOAuth}}
{{/authMethods}}
{{/hasAuthMethods}}
let method = hyper::Method::{{httpMethod}};
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
{{#queryParams}}
query.append_pair("{{baseName}}", &{{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
{{/queryParams}}
{{#hasAuthMethods}}
for (key, val) in &auth_query {
query.append_pair(key, val);
}
{{/hasAuthMethods}}
query.finish()
};
let uri_str = format!("{}{{{path}}}?{}", configuration.base_path, query_string{{#pathParams}}, {{baseName}}={{paramName}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}}{{/pathParams}});
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
{{#hasHeaderParams}}
{
let mut headers = req.headers_mut();
{{#headerParams}}
headers.set_raw("{{baseName}}", {{paramName}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}});
{{/headerParams}}
}
{{/hasHeaderParams}}
{{#hasAuthMethods}} {{#hasAuthMethods}}
for (key, val) in auth_headers { {{#authMethods}}
req.headers_mut().set_raw(key, val); {{#isApiKey}}
} .with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{
in_header: {{#isKeyInHeader}}true{{/isKeyInHeader}}{{^isKeyInHeader}}false{{/isKeyInHeader}},
in_query: {{#isKeyInQuery}}true{{/isKeyInQuery}}{{^isKeyInQuery}}false{{/isKeyInQuery}},
param_name: "{{{keyParamName}}}".to_owned(),
}))
{{/isApiKey}}
{{#isBasic}}
.with_auth(__internal_request::Auth::Basic)
{{/isBasic}}
{{#isOAuth}}
.with_auth(__internal_request::Auth::Oauth)
{{/isOAuth}}
{{/authMethods}}
{{/hasAuthMethods}} {{/hasAuthMethods}}
{{#queryParams}}
.with_query_param("{{baseName}}".to_string(), {{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string())
{{/queryParams}}
{{#pathParams}}
.with_path_param("{{baseName}}".to_string(), {{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string())
{{/pathParams}}
{{#hasHeaderParams}}
{{#headerParams}}
.with_header_param("{{baseName}}".to_string(), {{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string())
{{/headerParams}}
{{/hasHeaderParams}}
{{#hasFormParams}}
{{#formParams}}
{{#isFile}}
.with_form_param("{{baseName}}".to_string(), unimplemented!())
{{/isFile}}
{{^isFile}}
.with_form_param("{{baseName}}".to_string(), {{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string())
{{/isFile}}
{{/formParams}}
{{/hasFormParams}}
{{#hasBodyParam}} {{#hasBodyParam}}
{{#bodyParams}} {{#bodyParams}}
let serialized = serde_json::to_string(&{{paramName}}).unwrap(); .with_body_param({{paramName}})
req.headers_mut().set(hyper::header::ContentType::json());
req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64));
req.set_body(serialized);
{{/bodyParams}} {{/bodyParams}}
{{/hasBodyParam}} {{/hasBodyParam}}
// send request
Box::new(
configuration.client.request(req)
.map_err(|e| Error::from(e))
.and_then(|resp| {
let status = resp.status();
resp.body().concat2()
.and_then(move |body| Ok((status, body)))
.map_err(|e| Error::from(e))
})
.and_then(|(status, body)| {
if status.is_success() {
Ok(body)
} else {
Err(Error::from((status, &*body)))
}
})
{{^returnType}} {{^returnType}}
.and_then(|_| futures::future::ok(())) .returns_nothing()
{{/returnType}} {{/returnType}}
{{#returnType}} .execute(self.configuration.borrow())
.and_then(|body| {
let parsed: Result<{{{returnType}}}, _> = serde_json::from_slice(&body);
parsed.map_err(|e| Error::from(e))
})
{{/returnType}}
)
} }
{{/operation}} {{/operation}}

View File

@ -4,6 +4,7 @@ use serde_json;
#[derive(Debug)] #[derive(Debug)]
pub enum Error<T> { pub enum Error<T> {
UriError(hyper::error::UriError),
Hyper(hyper::Error), Hyper(hyper::Error),
Serde(serde_json::Error), Serde(serde_json::Error),
ApiError(ApiError<T>), ApiError(ApiError<T>),
@ -50,6 +51,8 @@ impl<T> From<serde_json::Error> for Error<T> {
use super::models::*; use super::models::*;
mod request;
{{#apiInfo}} {{#apiInfo}}
{{#apis}} {{#apis}}
mod {{classFilename}}; mod {{classFilename}};

View File

@ -0,0 +1,238 @@
use std::borrow::Cow;
use std::collections::HashMap;
use super::{configuration, Error};
use futures;
use futures::{Future, Stream};
use hyper;
use hyper::header::UserAgent;
use serde;
use serde_json;
pub(crate) struct ApiKey {
pub in_header: bool,
pub in_query: bool,
pub param_name: String,
}
impl ApiKey {
fn key(&self, prefix: &Option<String>, key: &str) -> String {
match prefix {
None => key.to_owned(),
Some(ref prefix) => format!("{} {}", prefix, key),
}
}
}
pub(crate) enum Auth {
None,
ApiKey(ApiKey),
Basic,
Oauth,
}
pub(crate) struct Request {
auth: Auth,
method: hyper::Method,
path: String,
query_params: HashMap<String, String>,
no_return_type: bool,
path_params: HashMap<String, String>,
form_params: HashMap<String, String>,
header_params: HashMap<String, String>,
// TODO: multiple body params are possible technically, but not supported here.
serialized_body: Option<String>,
}
impl Request {
pub fn new(method: hyper::Method, path: String) -> Self {
Request {
auth: Auth::None,
method: method,
path: path,
query_params: HashMap::new(),
path_params: HashMap::new(),
form_params: HashMap::new(),
header_params: HashMap::new(),
serialized_body: None,
no_return_type: false,
}
}
pub fn with_body_param<T: serde::Serialize>(mut self, param: T) -> Self {
self.serialized_body = Some(serde_json::to_string(&param).unwrap());
self
}
pub fn with_header_param(mut self, basename: String, param: String) -> Self {
self.header_params.insert(basename, param);
self
}
pub fn with_query_param(mut self, basename: String, param: String) -> Self {
self.query_params.insert(basename, param);
self
}
pub fn with_path_param(mut self, basename: String, param: String) -> Self {
self.path_params.insert(basename, param);
self
}
pub fn with_form_param(mut self, basename: String, param: String) -> Self {
self.form_params.insert(basename, param);
self
}
pub fn returns_nothing(mut self) -> Self {
self.no_return_type = true;
self
}
pub fn with_auth(mut self, auth: Auth) -> Self {
self.auth = auth;
self
}
pub fn execute<'a, C, U>(
self,
conf: &configuration::Configuration<C>,
) -> Box<Future<Item = U, Error = Error<serde_json::Value>> + 'a>
where
C: hyper::client::Connect,
U: Sized + 'a,
for<'de> U: serde::Deserialize<'de>,
{
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;
for (k, v) in self.path_params {
// replace {id} with the value of the id path param
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 {
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 query_string_str = query_string.finish();
if query_string_str != "" {
uri_str += "?";
uri_str += &query_string_str;
}
let uri: hyper::Uri = match uri_str.parse() {
Err(e) => {
return Box::new(futures::future::err(Error::UriError(e)));
}
Ok(u) => u,
};
let mut req = hyper::Request::new(self.method, uri);
{
let req_headers = req.headers_mut();
if let Some(ref user_agent) = conf.user_agent {
req_headers.set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
req_headers.extend(headers.iter());
for (key, val) in raw_headers {
req_headers.set_raw(key, val);
}
}
if self.form_params.len() > 0 {
req.headers_mut().set(hyper::header::ContentType::form_url_encoded());
let mut enc = ::url::form_urlencoded::Serializer::new("".to_owned());
for (k, v) in self.form_params {
enc.append_pair(&k, &v);
}
req.set_body(enc.finish());
}
if let Some(body) = self.serialized_body {
req.headers_mut().set(hyper::header::ContentType::json());
req.headers_mut()
.set(hyper::header::ContentLength(body.len() as u64));
req.set_body(body);
}
let no_ret_type = self.no_return_type;
let res = conf.client
.request(req)
.map_err(|e| Error::from(e))
.and_then(|resp| {
let status = resp.status();
resp.body()
.concat2()
.and_then(move |body| Ok((status, body)))
.map_err(|e| Error::from(e))
})
.and_then(|(status, body)| {
if status.is_success() {
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

@ -1 +1 @@
3.0.0-SNAPSHOT 3.1.0

View File

@ -3,10 +3,10 @@ extern crate hyper;
extern crate petstore_client; extern crate petstore_client;
extern crate tokio_core; extern crate tokio_core;
use hyper::Client;
use hyper::client::HttpConnector;
use tokio_core::reactor::Core;
use futures::Future; use futures::Future;
use hyper::client::HttpConnector;
use hyper::Client;
use tokio_core::reactor::Core;
fn main() { fn main() {
let mut core = Core::new().expect("failed to init core"); let mut core = Core::new().expect("failed to init core");
@ -20,16 +20,16 @@ fn main() {
), ),
); );
let new_pet = petstore_client::models::Pet::new("barker".to_owned(), vec![]).with_id(1337); let new_pet = petstore_client::models::Pet::new("ferris".to_owned(), vec![]).with_id(128149);
let work = apicli let work = apicli
.pet_api() .pet_api()
.add_pet(new_pet) .add_pet(new_pet)
.and_then(|_| { .and_then(|_| {
apicli apicli
.pet_api() .pet_api()
.update_pet_with_form(1337, "barko", "escaped") .update_pet_with_form(128149, "ferris", "rusted")
}) })
.and_then(|_| apicli.pet_api().get_pet_by_id(1337)) .and_then(|_| apicli.pet_api().get_pet_by_id(128149))
.and_then(|pet| { .and_then(|pet| {
println!("pet: {:?}", pet); println!("pet: {:?}", pet);
futures::future::ok(()) futures::future::ok(())

View File

@ -3,12 +3,12 @@ extern crate hyper;
extern crate petstore_client; extern crate petstore_client;
extern crate tokio_core; extern crate tokio_core;
use hyper::Client;
use hyper::client::HttpConnector;
use tokio_core::reactor::Core;
use futures::Future; use futures::Future;
use hyper::client::HttpConnector;
use hyper::Client;
use petstore_client::apis::client::APIClient; use petstore_client::apis::client::APIClient;
use petstore_client::apis::Error; use petstore_client::apis::Error;
use tokio_core::reactor::Core;
fn main() { fn main() {
let mut core = Core::new().expect("failed to init core"); let mut core = Core::new().expect("failed to init core");

View File

@ -4,6 +4,7 @@ use serde_json;
#[derive(Debug)] #[derive(Debug)]
pub enum Error<T> { pub enum Error<T> {
UriError(hyper::error::UriError),
Hyper(hyper::Error), Hyper(hyper::Error),
Serde(serde_json::Error), Serde(serde_json::Error),
ApiError(ApiError<T>), ApiError(ApiError<T>),
@ -50,6 +51,8 @@ impl<T> From<serde_json::Error> for Error<T> {
use super::models::*; use super::models::*;
mod request;
mod pet_api; mod pet_api;
pub use self::pet_api::{ PetApi, PetApiClient }; pub use self::pet_api::{ PetApi, PetApiClient };
mod store_api; mod store_api;

View File

@ -10,17 +10,13 @@
use std::rc::Rc; use std::rc::Rc;
use std::borrow::Borrow; use std::borrow::Borrow;
use std::borrow::Cow;
use std::collections::HashMap;
use hyper; use hyper;
use serde_json; use serde_json;
use futures; use futures::Future;
use futures::{Future, Stream};
use hyper::header::UserAgent;
use super::{Error, configuration}; use super::{Error, configuration};
use super::request as __internal_request;
pub struct PetApiClient<C: hyper::client::Connect> { pub struct PetApiClient<C: hyper::client::Connect> {
configuration: Rc<configuration::Configuration<C>>, configuration: Rc<configuration::Configuration<C>>,
@ -48,533 +44,72 @@ pub trait PetApi {
impl<C: hyper::client::Connect>PetApi for PetApiClient<C> { impl<C: hyper::client::Connect>PetApi for PetApiClient<C> {
fn add_pet(&self, pet: ::models::Pet) -> Box<Future<Item = (), Error = Error<serde_json::Value>>> { fn add_pet(&self, pet: ::models::Pet) -> Box<Future<Item = (), Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow(); __internal_request::Request::new(hyper::Method::Post, "/pet".to_string())
.with_auth(__internal_request::Auth::Oauth)
let mut auth_headers = HashMap::<String, String>::new(); .with_body_param(pet)
let mut auth_query = HashMap::<String, String>::new(); .returns_nothing()
if let Some(ref token) = configuration.oauth_access_token { .execute(self.configuration.borrow())
let auth = hyper::header::Authorization(
hyper::header::Bearer {
token: token.to_owned(),
}
);
auth_headers.insert("Authorization".to_owned(), auth.to_string());
};
let method = hyper::Method::Post;
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
for (key, val) in &auth_query {
query.append_pair(key, val);
}
query.finish()
};
let uri_str = format!("{}/pet?{}", configuration.base_path, query_string);
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
for (key, val) in auth_headers {
req.headers_mut().set_raw(key, val);
}
let serialized = serde_json::to_string(&pet).unwrap();
req.headers_mut().set(hyper::header::ContentType::json());
req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64));
req.set_body(serialized);
// send request
Box::new(
configuration.client.request(req)
.map_err(|e| Error::from(e))
.and_then(|resp| {
let status = resp.status();
resp.body().concat2()
.and_then(move |body| Ok((status, body)))
.map_err(|e| Error::from(e))
})
.and_then(|(status, body)| {
if status.is_success() {
Ok(body)
} else {
Err(Error::from((status, &*body)))
}
})
.and_then(|_| futures::future::ok(()))
)
} }
fn delete_pet(&self, pet_id: i64, api_key: &str) -> Box<Future<Item = (), Error = Error<serde_json::Value>>> { fn delete_pet(&self, pet_id: i64, api_key: &str) -> Box<Future<Item = (), Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow(); __internal_request::Request::new(hyper::Method::Delete, "/pet/{petId}".to_string())
.with_auth(__internal_request::Auth::Oauth)
let mut auth_headers = HashMap::<String, String>::new(); .with_path_param("petId".to_string(), pet_id.to_string())
let mut auth_query = HashMap::<String, String>::new(); .with_header_param("api_key".to_string(), api_key.to_string())
if let Some(ref token) = configuration.oauth_access_token { .returns_nothing()
let auth = hyper::header::Authorization( .execute(self.configuration.borrow())
hyper::header::Bearer {
token: token.to_owned(),
}
);
auth_headers.insert("Authorization".to_owned(), auth.to_string());
};
let method = hyper::Method::Delete;
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
for (key, val) in &auth_query {
query.append_pair(key, val);
}
query.finish()
};
let uri_str = format!("{}/pet/{petId}?{}", configuration.base_path, query_string, petId=pet_id);
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
{
let mut headers = req.headers_mut();
headers.set_raw("api_key", api_key);
}
for (key, val) in auth_headers {
req.headers_mut().set_raw(key, val);
}
// send request
Box::new(
configuration.client.request(req)
.map_err(|e| Error::from(e))
.and_then(|resp| {
let status = resp.status();
resp.body().concat2()
.and_then(move |body| Ok((status, body)))
.map_err(|e| Error::from(e))
})
.and_then(|(status, body)| {
if status.is_success() {
Ok(body)
} else {
Err(Error::from((status, &*body)))
}
})
.and_then(|_| futures::future::ok(()))
)
} }
fn find_pets_by_status(&self, status: Vec<String>) -> Box<Future<Item = Vec<::models::Pet>, Error = Error<serde_json::Value>>> { fn find_pets_by_status(&self, status: Vec<String>) -> Box<Future<Item = Vec<::models::Pet>, Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow(); __internal_request::Request::new(hyper::Method::Get, "/pet/findByStatus".to_string())
.with_auth(__internal_request::Auth::Oauth)
let mut auth_headers = HashMap::<String, String>::new(); .with_query_param("status".to_string(), status.join(",").to_string())
let mut auth_query = HashMap::<String, String>::new(); .execute(self.configuration.borrow())
if let Some(ref token) = configuration.oauth_access_token {
let auth = hyper::header::Authorization(
hyper::header::Bearer {
token: token.to_owned(),
}
);
auth_headers.insert("Authorization".to_owned(), auth.to_string());
};
let method = hyper::Method::Get;
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
query.append_pair("status", &status.join(",").to_string());
for (key, val) in &auth_query {
query.append_pair(key, val);
}
query.finish()
};
let uri_str = format!("{}/pet/findByStatus?{}", configuration.base_path, query_string);
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
for (key, val) in auth_headers {
req.headers_mut().set_raw(key, val);
}
// send request
Box::new(
configuration.client.request(req)
.map_err(|e| Error::from(e))
.and_then(|resp| {
let status = resp.status();
resp.body().concat2()
.and_then(move |body| Ok((status, body)))
.map_err(|e| Error::from(e))
})
.and_then(|(status, body)| {
if status.is_success() {
Ok(body)
} else {
Err(Error::from((status, &*body)))
}
})
.and_then(|body| {
let parsed: Result<Vec<::models::Pet>, _> = serde_json::from_slice(&body);
parsed.map_err(|e| Error::from(e))
})
)
} }
fn find_pets_by_tags(&self, tags: Vec<String>) -> Box<Future<Item = Vec<::models::Pet>, Error = Error<serde_json::Value>>> { fn find_pets_by_tags(&self, tags: Vec<String>) -> Box<Future<Item = Vec<::models::Pet>, Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow(); __internal_request::Request::new(hyper::Method::Get, "/pet/findByTags".to_string())
.with_auth(__internal_request::Auth::Oauth)
let mut auth_headers = HashMap::<String, String>::new(); .with_query_param("tags".to_string(), tags.join(",").to_string())
let mut auth_query = HashMap::<String, String>::new(); .execute(self.configuration.borrow())
if let Some(ref token) = configuration.oauth_access_token {
let auth = hyper::header::Authorization(
hyper::header::Bearer {
token: token.to_owned(),
}
);
auth_headers.insert("Authorization".to_owned(), auth.to_string());
};
let method = hyper::Method::Get;
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
query.append_pair("tags", &tags.join(",").to_string());
for (key, val) in &auth_query {
query.append_pair(key, val);
}
query.finish()
};
let uri_str = format!("{}/pet/findByTags?{}", configuration.base_path, query_string);
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
for (key, val) in auth_headers {
req.headers_mut().set_raw(key, val);
}
// send request
Box::new(
configuration.client.request(req)
.map_err(|e| Error::from(e))
.and_then(|resp| {
let status = resp.status();
resp.body().concat2()
.and_then(move |body| Ok((status, body)))
.map_err(|e| Error::from(e))
})
.and_then(|(status, body)| {
if status.is_success() {
Ok(body)
} else {
Err(Error::from((status, &*body)))
}
})
.and_then(|body| {
let parsed: Result<Vec<::models::Pet>, _> = serde_json::from_slice(&body);
parsed.map_err(|e| Error::from(e))
})
)
} }
fn get_pet_by_id(&self, pet_id: i64) -> Box<Future<Item = ::models::Pet, Error = Error<serde_json::Value>>> { fn get_pet_by_id(&self, pet_id: i64) -> Box<Future<Item = ::models::Pet, Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow(); __internal_request::Request::new(hyper::Method::Get, "/pet/{petId}".to_string())
.with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{
let mut auth_headers = HashMap::<String, String>::new(); in_header: true,
let mut auth_query = HashMap::<String, String>::new(); in_query: false,
if let Some(ref apikey) = configuration.api_key { param_name: "api_key".to_owned(),
let key = apikey.key.clone(); }))
let val = match apikey.prefix { .with_path_param("petId".to_string(), pet_id.to_string())
Some(ref prefix) => format!("{} {}", prefix, key), .execute(self.configuration.borrow())
None => key,
};
auth_headers.insert("api_key".to_owned(), val);
};
let method = hyper::Method::Get;
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
for (key, val) in &auth_query {
query.append_pair(key, val);
}
query.finish()
};
let uri_str = format!("{}/pet/{petId}?{}", configuration.base_path, query_string, petId=pet_id);
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
for (key, val) in auth_headers {
req.headers_mut().set_raw(key, val);
}
// send request
Box::new(
configuration.client.request(req)
.map_err(|e| Error::from(e))
.and_then(|resp| {
let status = resp.status();
resp.body().concat2()
.and_then(move |body| Ok((status, body)))
.map_err(|e| Error::from(e))
})
.and_then(|(status, body)| {
if status.is_success() {
Ok(body)
} else {
Err(Error::from((status, &*body)))
}
})
.and_then(|body| {
let parsed: Result<::models::Pet, _> = serde_json::from_slice(&body);
parsed.map_err(|e| Error::from(e))
})
)
} }
fn update_pet(&self, pet: ::models::Pet) -> Box<Future<Item = (), Error = Error<serde_json::Value>>> { fn update_pet(&self, pet: ::models::Pet) -> Box<Future<Item = (), Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow(); __internal_request::Request::new(hyper::Method::Put, "/pet".to_string())
.with_auth(__internal_request::Auth::Oauth)
let mut auth_headers = HashMap::<String, String>::new(); .with_body_param(pet)
let mut auth_query = HashMap::<String, String>::new(); .returns_nothing()
if let Some(ref token) = configuration.oauth_access_token { .execute(self.configuration.borrow())
let auth = hyper::header::Authorization(
hyper::header::Bearer {
token: token.to_owned(),
}
);
auth_headers.insert("Authorization".to_owned(), auth.to_string());
};
let method = hyper::Method::Put;
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
for (key, val) in &auth_query {
query.append_pair(key, val);
}
query.finish()
};
let uri_str = format!("{}/pet?{}", configuration.base_path, query_string);
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
for (key, val) in auth_headers {
req.headers_mut().set_raw(key, val);
}
let serialized = serde_json::to_string(&pet).unwrap();
req.headers_mut().set(hyper::header::ContentType::json());
req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64));
req.set_body(serialized);
// send request
Box::new(
configuration.client.request(req)
.map_err(|e| Error::from(e))
.and_then(|resp| {
let status = resp.status();
resp.body().concat2()
.and_then(move |body| Ok((status, body)))
.map_err(|e| Error::from(e))
})
.and_then(|(status, body)| {
if status.is_success() {
Ok(body)
} else {
Err(Error::from((status, &*body)))
}
})
.and_then(|_| futures::future::ok(()))
)
} }
fn update_pet_with_form(&self, pet_id: i64, name: &str, status: &str) -> Box<Future<Item = (), Error = Error<serde_json::Value>>> { fn update_pet_with_form(&self, pet_id: i64, name: &str, status: &str) -> Box<Future<Item = (), Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow(); __internal_request::Request::new(hyper::Method::Post, "/pet/{petId}".to_string())
.with_auth(__internal_request::Auth::Oauth)
let mut auth_headers = HashMap::<String, String>::new(); .with_path_param("petId".to_string(), pet_id.to_string())
let mut auth_query = HashMap::<String, String>::new(); .with_form_param("name".to_string(), name.to_string())
if let Some(ref token) = configuration.oauth_access_token { .with_form_param("status".to_string(), status.to_string())
let auth = hyper::header::Authorization( .returns_nothing()
hyper::header::Bearer { .execute(self.configuration.borrow())
token: token.to_owned(),
}
);
auth_headers.insert("Authorization".to_owned(), auth.to_string());
};
let method = hyper::Method::Post;
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
for (key, val) in &auth_query {
query.append_pair(key, val);
}
query.finish()
};
let uri_str = format!("{}/pet/{petId}?{}", configuration.base_path, query_string, petId=pet_id);
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
for (key, val) in auth_headers {
req.headers_mut().set_raw(key, val);
}
// send request
Box::new(
configuration.client.request(req)
.map_err(|e| Error::from(e))
.and_then(|resp| {
let status = resp.status();
resp.body().concat2()
.and_then(move |body| Ok((status, body)))
.map_err(|e| Error::from(e))
})
.and_then(|(status, body)| {
if status.is_success() {
Ok(body)
} else {
Err(Error::from((status, &*body)))
}
})
.and_then(|_| futures::future::ok(()))
)
} }
fn upload_file(&self, pet_id: i64, additional_metadata: &str, file: ::models::File) -> Box<Future<Item = ::models::ApiResponse, Error = Error<serde_json::Value>>> { fn upload_file(&self, pet_id: i64, additional_metadata: &str, file: ::models::File) -> Box<Future<Item = ::models::ApiResponse, Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow(); __internal_request::Request::new(hyper::Method::Post, "/pet/{petId}/uploadImage".to_string())
.with_auth(__internal_request::Auth::Oauth)
let mut auth_headers = HashMap::<String, String>::new(); .with_path_param("petId".to_string(), pet_id.to_string())
let mut auth_query = HashMap::<String, String>::new(); .with_form_param("additionalMetadata".to_string(), additional_metadata.to_string())
if let Some(ref token) = configuration.oauth_access_token { .with_form_param("file".to_string(), unimplemented!())
let auth = hyper::header::Authorization( .execute(self.configuration.borrow())
hyper::header::Bearer {
token: token.to_owned(),
}
);
auth_headers.insert("Authorization".to_owned(), auth.to_string());
};
let method = hyper::Method::Post;
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
for (key, val) in &auth_query {
query.append_pair(key, val);
}
query.finish()
};
let uri_str = format!("{}/pet/{petId}/uploadImage?{}", configuration.base_path, query_string, petId=pet_id);
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
for (key, val) in auth_headers {
req.headers_mut().set_raw(key, val);
}
// send request
Box::new(
configuration.client.request(req)
.map_err(|e| Error::from(e))
.and_then(|resp| {
let status = resp.status();
resp.body().concat2()
.and_then(move |body| Ok((status, body)))
.map_err(|e| Error::from(e))
})
.and_then(|(status, body)| {
if status.is_success() {
Ok(body)
} else {
Err(Error::from((status, &*body)))
}
})
.and_then(|body| {
let parsed: Result<::models::ApiResponse, _> = serde_json::from_slice(&body);
parsed.map_err(|e| Error::from(e))
})
)
} }
} }

View File

@ -0,0 +1,238 @@
use std::borrow::Cow;
use std::collections::HashMap;
use super::{configuration, Error};
use futures;
use futures::{Future, Stream};
use hyper;
use hyper::header::UserAgent;
use serde;
use serde_json;
pub(crate) struct ApiKey {
pub in_header: bool,
pub in_query: bool,
pub param_name: String,
}
impl ApiKey {
fn key(&self, prefix: &Option<String>, key: &str) -> String {
match prefix {
None => key.to_owned(),
Some(ref prefix) => format!("{} {}", prefix, key),
}
}
}
pub(crate) enum Auth {
None,
ApiKey(ApiKey),
Basic,
Oauth,
}
pub(crate) struct Request {
auth: Auth,
method: hyper::Method,
path: String,
query_params: HashMap<String, String>,
no_return_type: bool,
path_params: HashMap<String, String>,
form_params: HashMap<String, String>,
header_params: HashMap<String, String>,
// TODO: multiple body params are possible technically, but not supported here.
serialized_body: Option<String>,
}
impl Request {
pub fn new(method: hyper::Method, path: String) -> Self {
Request {
auth: Auth::None,
method: method,
path: path,
query_params: HashMap::new(),
path_params: HashMap::new(),
form_params: HashMap::new(),
header_params: HashMap::new(),
serialized_body: None,
no_return_type: false,
}
}
pub fn with_body_param<T: serde::Serialize>(mut self, param: T) -> Self {
self.serialized_body = Some(serde_json::to_string(&param).unwrap());
self
}
pub fn with_header_param(mut self, basename: String, param: String) -> Self {
self.header_params.insert(basename, param);
self
}
pub fn with_query_param(mut self, basename: String, param: String) -> Self {
self.query_params.insert(basename, param);
self
}
pub fn with_path_param(mut self, basename: String, param: String) -> Self {
self.path_params.insert(basename, param);
self
}
pub fn with_form_param(mut self, basename: String, param: String) -> Self {
self.form_params.insert(basename, param);
self
}
pub fn returns_nothing(mut self) -> Self {
self.no_return_type = true;
self
}
pub fn with_auth(mut self, auth: Auth) -> Self {
self.auth = auth;
self
}
pub fn execute<'a, C, U>(
self,
conf: &configuration::Configuration<C>,
) -> Box<Future<Item = U, Error = Error<serde_json::Value>> + 'a>
where
C: hyper::client::Connect,
U: Sized + 'a,
for<'de> U: serde::Deserialize<'de>,
{
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;
for (k, v) in self.path_params {
// replace {id} with the value of the id path param
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 {
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 query_string_str = query_string.finish();
if query_string_str != "" {
uri_str += "?";
uri_str += &query_string_str;
}
let uri: hyper::Uri = match uri_str.parse() {
Err(e) => {
return Box::new(futures::future::err(Error::UriError(e)));
}
Ok(u) => u,
};
let mut req = hyper::Request::new(self.method, uri);
{
let req_headers = req.headers_mut();
if let Some(ref user_agent) = conf.user_agent {
req_headers.set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
req_headers.extend(headers.iter());
for (key, val) in raw_headers {
req_headers.set_raw(key, val);
}
}
if self.form_params.len() > 0 {
req.headers_mut().set(hyper::header::ContentType::form_url_encoded());
let mut enc = ::url::form_urlencoded::Serializer::new("".to_owned());
for (k, v) in self.form_params {
enc.append_pair(&k, &v);
}
req.set_body(enc.finish());
}
if let Some(body) = self.serialized_body {
req.headers_mut().set(hyper::header::ContentType::json());
req.headers_mut()
.set(hyper::header::ContentLength(body.len() as u64));
req.set_body(body);
}
let no_ret_type = self.no_return_type;
let res = conf.client
.request(req)
.map_err(|e| Error::from(e))
.and_then(|resp| {
let status = resp.status();
resp.body()
.concat2()
.and_then(move |body| Ok((status, body)))
.map_err(|e| Error::from(e))
})
.and_then(|(status, body)| {
if status.is_success() {
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

@ -10,17 +10,13 @@
use std::rc::Rc; use std::rc::Rc;
use std::borrow::Borrow; use std::borrow::Borrow;
use std::borrow::Cow;
use std::collections::HashMap;
use hyper; use hyper;
use serde_json; use serde_json;
use futures; use futures::Future;
use futures::{Future, Stream};
use hyper::header::UserAgent;
use super::{Error, configuration}; use super::{Error, configuration};
use super::request as __internal_request;
pub struct StoreApiClient<C: hyper::client::Connect> { pub struct StoreApiClient<C: hyper::client::Connect> {
configuration: Rc<configuration::Configuration<C>>, configuration: Rc<configuration::Configuration<C>>,
@ -44,220 +40,32 @@ pub trait StoreApi {
impl<C: hyper::client::Connect>StoreApi for StoreApiClient<C> { impl<C: hyper::client::Connect>StoreApi for StoreApiClient<C> {
fn delete_order(&self, order_id: &str) -> Box<Future<Item = (), Error = Error<serde_json::Value>>> { fn delete_order(&self, order_id: &str) -> Box<Future<Item = (), Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow(); __internal_request::Request::new(hyper::Method::Delete, "/store/order/{orderId}".to_string())
.with_path_param("orderId".to_string(), order_id.to_string())
let method = hyper::Method::Delete; .returns_nothing()
.execute(self.configuration.borrow())
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
query.finish()
};
let uri_str = format!("{}/store/order/{orderId}?{}", configuration.base_path, query_string, orderId=order_id);
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
// send request
Box::new(
configuration.client.request(req)
.map_err(|e| Error::from(e))
.and_then(|resp| {
let status = resp.status();
resp.body().concat2()
.and_then(move |body| Ok((status, body)))
.map_err(|e| Error::from(e))
})
.and_then(|(status, body)| {
if status.is_success() {
Ok(body)
} else {
Err(Error::from((status, &*body)))
}
})
.and_then(|_| futures::future::ok(()))
)
} }
fn get_inventory(&self, ) -> Box<Future<Item = ::std::collections::HashMap<String, i32>, Error = Error<serde_json::Value>>> { fn get_inventory(&self, ) -> Box<Future<Item = ::std::collections::HashMap<String, i32>, Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow(); __internal_request::Request::new(hyper::Method::Get, "/store/inventory".to_string())
.with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{
let mut auth_headers = HashMap::<String, String>::new(); in_header: true,
let mut auth_query = HashMap::<String, String>::new(); in_query: false,
if let Some(ref apikey) = configuration.api_key { param_name: "api_key".to_owned(),
let key = apikey.key.clone(); }))
let val = match apikey.prefix { .execute(self.configuration.borrow())
Some(ref prefix) => format!("{} {}", prefix, key),
None => key,
};
auth_headers.insert("api_key".to_owned(), val);
};
let method = hyper::Method::Get;
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
for (key, val) in &auth_query {
query.append_pair(key, val);
}
query.finish()
};
let uri_str = format!("{}/store/inventory?{}", configuration.base_path, query_string);
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
for (key, val) in auth_headers {
req.headers_mut().set_raw(key, val);
}
// send request
Box::new(
configuration.client.request(req)
.map_err(|e| Error::from(e))
.and_then(|resp| {
let status = resp.status();
resp.body().concat2()
.and_then(move |body| Ok((status, body)))
.map_err(|e| Error::from(e))
})
.and_then(|(status, body)| {
if status.is_success() {
Ok(body)
} else {
Err(Error::from((status, &*body)))
}
})
.and_then(|body| {
let parsed: Result<::std::collections::HashMap<String, i32>, _> = serde_json::from_slice(&body);
parsed.map_err(|e| Error::from(e))
})
)
} }
fn get_order_by_id(&self, order_id: i64) -> Box<Future<Item = ::models::Order, Error = Error<serde_json::Value>>> { fn get_order_by_id(&self, order_id: i64) -> Box<Future<Item = ::models::Order, Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow(); __internal_request::Request::new(hyper::Method::Get, "/store/order/{orderId}".to_string())
.with_path_param("orderId".to_string(), order_id.to_string())
let method = hyper::Method::Get; .execute(self.configuration.borrow())
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
query.finish()
};
let uri_str = format!("{}/store/order/{orderId}?{}", configuration.base_path, query_string, orderId=order_id);
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
// send request
Box::new(
configuration.client.request(req)
.map_err(|e| Error::from(e))
.and_then(|resp| {
let status = resp.status();
resp.body().concat2()
.and_then(move |body| Ok((status, body)))
.map_err(|e| Error::from(e))
})
.and_then(|(status, body)| {
if status.is_success() {
Ok(body)
} else {
Err(Error::from((status, &*body)))
}
})
.and_then(|body| {
let parsed: Result<::models::Order, _> = serde_json::from_slice(&body);
parsed.map_err(|e| Error::from(e))
})
)
} }
fn place_order(&self, order: ::models::Order) -> Box<Future<Item = ::models::Order, Error = Error<serde_json::Value>>> { fn place_order(&self, order: ::models::Order) -> Box<Future<Item = ::models::Order, Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow(); __internal_request::Request::new(hyper::Method::Post, "/store/order".to_string())
.with_body_param(order)
let method = hyper::Method::Post; .execute(self.configuration.borrow())
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
query.finish()
};
let uri_str = format!("{}/store/order?{}", configuration.base_path, query_string);
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
let serialized = serde_json::to_string(&order).unwrap();
req.headers_mut().set(hyper::header::ContentType::json());
req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64));
req.set_body(serialized);
// send request
Box::new(
configuration.client.request(req)
.map_err(|e| Error::from(e))
.and_then(|resp| {
let status = resp.status();
resp.body().concat2()
.and_then(move |body| Ok((status, body)))
.map_err(|e| Error::from(e))
})
.and_then(|(status, body)| {
if status.is_success() {
Ok(body)
} else {
Err(Error::from((status, &*body)))
}
})
.and_then(|body| {
let parsed: Result<::models::Order, _> = serde_json::from_slice(&body);
parsed.map_err(|e| Error::from(e))
})
)
} }
} }

View File

@ -10,17 +10,13 @@
use std::rc::Rc; use std::rc::Rc;
use std::borrow::Borrow; use std::borrow::Borrow;
use std::borrow::Cow;
use std::collections::HashMap;
use hyper; use hyper;
use serde_json; use serde_json;
use futures; use futures::Future;
use futures::{Future, Stream};
use hyper::header::UserAgent;
use super::{Error, configuration}; use super::{Error, configuration};
use super::request as __internal_request;
pub struct UserApiClient<C: hyper::client::Connect> { pub struct UserApiClient<C: hyper::client::Connect> {
configuration: Rc<configuration::Configuration<C>>, configuration: Rc<configuration::Configuration<C>>,
@ -48,403 +44,58 @@ pub trait UserApi {
impl<C: hyper::client::Connect>UserApi for UserApiClient<C> { impl<C: hyper::client::Connect>UserApi for UserApiClient<C> {
fn create_user(&self, user: ::models::User) -> Box<Future<Item = (), Error = Error<serde_json::Value>>> { fn create_user(&self, user: ::models::User) -> Box<Future<Item = (), Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow(); __internal_request::Request::new(hyper::Method::Post, "/user".to_string())
.with_body_param(user)
let method = hyper::Method::Post; .returns_nothing()
.execute(self.configuration.borrow())
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
query.finish()
};
let uri_str = format!("{}/user?{}", configuration.base_path, query_string);
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
let serialized = serde_json::to_string(&user).unwrap();
req.headers_mut().set(hyper::header::ContentType::json());
req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64));
req.set_body(serialized);
// send request
Box::new(
configuration.client.request(req)
.map_err(|e| Error::from(e))
.and_then(|resp| {
let status = resp.status();
resp.body().concat2()
.and_then(move |body| Ok((status, body)))
.map_err(|e| Error::from(e))
})
.and_then(|(status, body)| {
if status.is_success() {
Ok(body)
} else {
Err(Error::from((status, &*body)))
}
})
.and_then(|_| futures::future::ok(()))
)
} }
fn create_users_with_array_input(&self, user: Vec<::models::User>) -> Box<Future<Item = (), Error = Error<serde_json::Value>>> { fn create_users_with_array_input(&self, user: Vec<::models::User>) -> Box<Future<Item = (), Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow(); __internal_request::Request::new(hyper::Method::Post, "/user/createWithArray".to_string())
.with_body_param(user)
let method = hyper::Method::Post; .returns_nothing()
.execute(self.configuration.borrow())
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
query.finish()
};
let uri_str = format!("{}/user/createWithArray?{}", configuration.base_path, query_string);
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
let serialized = serde_json::to_string(&user).unwrap();
req.headers_mut().set(hyper::header::ContentType::json());
req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64));
req.set_body(serialized);
// send request
Box::new(
configuration.client.request(req)
.map_err(|e| Error::from(e))
.and_then(|resp| {
let status = resp.status();
resp.body().concat2()
.and_then(move |body| Ok((status, body)))
.map_err(|e| Error::from(e))
})
.and_then(|(status, body)| {
if status.is_success() {
Ok(body)
} else {
Err(Error::from((status, &*body)))
}
})
.and_then(|_| futures::future::ok(()))
)
} }
fn create_users_with_list_input(&self, user: Vec<::models::User>) -> Box<Future<Item = (), Error = Error<serde_json::Value>>> { fn create_users_with_list_input(&self, user: Vec<::models::User>) -> Box<Future<Item = (), Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow(); __internal_request::Request::new(hyper::Method::Post, "/user/createWithList".to_string())
.with_body_param(user)
let method = hyper::Method::Post; .returns_nothing()
.execute(self.configuration.borrow())
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
query.finish()
};
let uri_str = format!("{}/user/createWithList?{}", configuration.base_path, query_string);
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
let serialized = serde_json::to_string(&user).unwrap();
req.headers_mut().set(hyper::header::ContentType::json());
req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64));
req.set_body(serialized);
// send request
Box::new(
configuration.client.request(req)
.map_err(|e| Error::from(e))
.and_then(|resp| {
let status = resp.status();
resp.body().concat2()
.and_then(move |body| Ok((status, body)))
.map_err(|e| Error::from(e))
})
.and_then(|(status, body)| {
if status.is_success() {
Ok(body)
} else {
Err(Error::from((status, &*body)))
}
})
.and_then(|_| futures::future::ok(()))
)
} }
fn delete_user(&self, username: &str) -> Box<Future<Item = (), Error = Error<serde_json::Value>>> { fn delete_user(&self, username: &str) -> Box<Future<Item = (), Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow(); __internal_request::Request::new(hyper::Method::Delete, "/user/{username}".to_string())
.with_path_param("username".to_string(), username.to_string())
let method = hyper::Method::Delete; .returns_nothing()
.execute(self.configuration.borrow())
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
query.finish()
};
let uri_str = format!("{}/user/{username}?{}", configuration.base_path, query_string, username=username);
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
// send request
Box::new(
configuration.client.request(req)
.map_err(|e| Error::from(e))
.and_then(|resp| {
let status = resp.status();
resp.body().concat2()
.and_then(move |body| Ok((status, body)))
.map_err(|e| Error::from(e))
})
.and_then(|(status, body)| {
if status.is_success() {
Ok(body)
} else {
Err(Error::from((status, &*body)))
}
})
.and_then(|_| futures::future::ok(()))
)
} }
fn get_user_by_name(&self, username: &str) -> Box<Future<Item = ::models::User, Error = Error<serde_json::Value>>> { fn get_user_by_name(&self, username: &str) -> Box<Future<Item = ::models::User, Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow(); __internal_request::Request::new(hyper::Method::Get, "/user/{username}".to_string())
.with_path_param("username".to_string(), username.to_string())
let method = hyper::Method::Get; .execute(self.configuration.borrow())
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
query.finish()
};
let uri_str = format!("{}/user/{username}?{}", configuration.base_path, query_string, username=username);
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
// send request
Box::new(
configuration.client.request(req)
.map_err(|e| Error::from(e))
.and_then(|resp| {
let status = resp.status();
resp.body().concat2()
.and_then(move |body| Ok((status, body)))
.map_err(|e| Error::from(e))
})
.and_then(|(status, body)| {
if status.is_success() {
Ok(body)
} else {
Err(Error::from((status, &*body)))
}
})
.and_then(|body| {
let parsed: Result<::models::User, _> = serde_json::from_slice(&body);
parsed.map_err(|e| Error::from(e))
})
)
} }
fn login_user(&self, username: &str, password: &str) -> Box<Future<Item = String, Error = Error<serde_json::Value>>> { fn login_user(&self, username: &str, password: &str) -> Box<Future<Item = String, Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow(); __internal_request::Request::new(hyper::Method::Get, "/user/login".to_string())
.with_query_param("username".to_string(), username.to_string())
let method = hyper::Method::Get; .with_query_param("password".to_string(), password.to_string())
.execute(self.configuration.borrow())
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
query.append_pair("username", &username.to_string());
query.append_pair("password", &password.to_string());
query.finish()
};
let uri_str = format!("{}/user/login?{}", configuration.base_path, query_string);
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
// send request
Box::new(
configuration.client.request(req)
.map_err(|e| Error::from(e))
.and_then(|resp| {
let status = resp.status();
resp.body().concat2()
.and_then(move |body| Ok((status, body)))
.map_err(|e| Error::from(e))
})
.and_then(|(status, body)| {
if status.is_success() {
Ok(body)
} else {
Err(Error::from((status, &*body)))
}
})
.and_then(|body| {
let parsed: Result<String, _> = serde_json::from_slice(&body);
parsed.map_err(|e| Error::from(e))
})
)
} }
fn logout_user(&self, ) -> Box<Future<Item = (), Error = Error<serde_json::Value>>> { fn logout_user(&self, ) -> Box<Future<Item = (), Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow(); __internal_request::Request::new(hyper::Method::Get, "/user/logout".to_string())
.returns_nothing()
let method = hyper::Method::Get; .execute(self.configuration.borrow())
let query_string = {
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
query.finish()
};
let uri_str = format!("{}/user/logout?{}", configuration.base_path, query_string);
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
// send request
Box::new(
configuration.client.request(req)
.map_err(|e| Error::from(e))
.and_then(|resp| {
let status = resp.status();
resp.body().concat2()
.and_then(move |body| Ok((status, body)))
.map_err(|e| Error::from(e))
})
.and_then(|(status, body)| {
if status.is_success() {
Ok(body)
} else {
Err(Error::from((status, &*body)))
}
})
.and_then(|_| futures::future::ok(()))
)
} }
fn update_user(&self, username: &str, user: ::models::User) -> Box<Future<Item = (), Error = Error<serde_json::Value>>> { fn update_user(&self, username: &str, user: ::models::User) -> Box<Future<Item = (), Error = Error<serde_json::Value>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow(); __internal_request::Request::new(hyper::Method::Put, "/user/{username}".to_string())
.with_path_param("username".to_string(), username.to_string())
let method = hyper::Method::Put; .with_body_param(user)
.returns_nothing()
let query_string = { .execute(self.configuration.borrow())
let mut query = ::url::form_urlencoded::Serializer::new(String::new());
query.finish()
};
let uri_str = format!("{}/user/{username}?{}", configuration.base_path, query_string, username=username);
// TODO(farcaller): handle error
// if let Err(e) = uri {
// return Box::new(futures::future::err(e));
// }
let mut uri: hyper::Uri = uri_str.parse().unwrap();
let mut req = hyper::Request::new(method, uri);
if let Some(ref user_agent) = configuration.user_agent {
req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
}
let serialized = serde_json::to_string(&user).unwrap();
req.headers_mut().set(hyper::header::ContentType::json());
req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64));
req.set_body(serialized);
// send request
Box::new(
configuration.client.request(req)
.map_err(|e| Error::from(e))
.and_then(|resp| {
let status = resp.status();
resp.body().concat2()
.and_then(move |body| Ok((status, body)))
.map_err(|e| Error::from(e))
})
.and_then(|(status, body)| {
if status.is_success() {
Ok(body)
} else {
Err(Error::from((status, &*body)))
}
})
.and_then(|_| futures::future::ok(()))
)
} }
} }