Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 3 commits into from
Jul 23, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,9 @@ public void processOpts() {
supportingFiles.add(new SupportingFile("configuration.mustache", apiFolder, "configuration.rs"));
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("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("lib.rs", "src", "lib.rs"));
supportingFiles.add(new SupportingFile("Cargo.mustache", "", "Cargo.toml"));
Expand Down
167 changes: 44 additions & 123 deletions modules/openapi-generator/src/main/resources/rust/api.mustache
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
{{>partial_header}}
use std::rc::Rc;
use std::borrow::Borrow;
use std::borrow::Cow;
use std::collections::HashMap;

use hyper;
use serde_json;
use futures;
use futures::{Future, Stream};

use hyper::header::UserAgent;
use futures::Future;

use super::{Error, configuration};
use super::request as __internal_request;

pub struct {{{classname}}}Client<C: hyper::client::Connect> {
configuration: Rc<configuration::Configuration<C>>,
Expand All @@ -38,129 +34,54 @@ impl<C: hyper::client::Connect>{{classname}} for {{classname}}Client<C> {
{{#operations}}
{{#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>>> {
let configuration: &configuration::Configuration<C> = self.configuration.borrow();

{{#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}}

__internal_request::Request::new(hyper::Method::{{httpMethod}}, "{{{path}}}".to_string())
{{#hasAuthMethods}}
for (key, val) in auth_headers {
req.headers_mut().set_raw(key, val);
}
{{#authMethods}}
{{#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}}

{{#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}}
{{#bodyParams}}
let serialized = serde_json::to_string(&{{paramName}}).unwrap();
req.headers_mut().set(hyper::header::ContentType::json());
req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64));
req.set_body(serialized);
.with_body_param({{paramName}})
{{/bodyParams}}
{{/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}}
.and_then(|_| futures::future::ok(()))
{{/returnType}}
{{#returnType}}
.and_then(|body| {
let parsed: Result<{{{returnType}}}, _> = serde_json::from_slice(&body);
parsed.map_err(|e| Error::from(e))
})
{{/returnType}}
)
{{^returnType}}
.returns_nothing()
{{/returnType}}
.execute(self.configuration.borrow())
}

{{/operation}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use serde_json;

#[derive(Debug)]
pub enum Error<T> {
UriError(hyper::error::UriError),
Hyper(hyper::Error),
Serde(serde_json::Error),
ApiError(ApiError<T>),
Expand Down Expand Up @@ -50,6 +51,8 @@ impl<T> From<serde_json::Error> for Error<T> {

use super::models::*;

mod request;

{{#apiInfo}}
{{#apis}}
mod {{classFilename}};
Expand Down
Loading