From ef3ee2d2f3b2ecbf911a1a55b46dbf5f84b6d663 Mon Sep 17 00:00:00 2001 From: Jimmy Cuadra Date: Sat, 13 May 2017 18:30:19 -0700 Subject: [PATCH] Add RequestBody and ResponseBody structs. --- src/request.rs | 34 ++++++++++++++++++++++++++++++++++ src/response.rs | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) diff --git a/src/request.rs b/src/request.rs index 214498e5..dbb45cd2 100644 --- a/src/request.rs +++ b/src/request.rs @@ -6,6 +6,12 @@ pub struct Request { fields: Vec, } +impl Request { + pub fn has_body_fields(&self) -> bool { + self.fields.iter().any(|field| field.is_body()) + } +} + impl From> for Request { fn from(fields: Vec) -> Self { let request_fields = fields.into_iter().map(|field| { @@ -68,6 +74,25 @@ impl ToTokens for Request { tokens.append("}"); } + + if self.has_body_fields() { + tokens.append(quote! { + /// Data in the request body. + #[derive(Debug, Serialize)] + struct RequestBody + }); + + tokens.append("{"); + + for request_field in self.fields.iter() { + match *request_field { + RequestField::Body(ref field) => field.to_tokens(&mut tokens), + _ => {} + } + } + + tokens.append("}"); + } } } @@ -78,3 +103,12 @@ pub enum RequestField { Path(String, Field), Query(Field), } + +impl RequestField { + fn is_body(&self) -> bool { + match *self { + RequestField::Body(_) => true, + _ => false, + } + } +} diff --git a/src/response.rs b/src/response.rs index 35bfcc06..0f1b15b3 100644 --- a/src/response.rs +++ b/src/response.rs @@ -6,6 +6,12 @@ pub struct Response { fields: Vec, } +impl Response { + pub fn has_body_fields(&self) -> bool { + self.fields.iter().any(|field| field.is_body()) + } +} + impl From> for Response { fn from(fields: Vec) -> Self { let response_fields = fields.into_iter().map(|field| { @@ -55,6 +61,25 @@ impl ToTokens for Response { tokens.append("}"); } + + if self.has_body_fields() { + tokens.append(quote! { + /// Data in the response body. + #[derive(Debug, Deserialize)] + struct ResponseBody + }); + + tokens.append("{"); + + for response_field in self.fields.iter() { + match *response_field { + ResponseField::Body(ref field) => field.to_tokens(&mut tokens), + _ => {} + } + } + + tokens.append("}"); + } } } @@ -63,3 +88,12 @@ pub enum ResponseField { Body(Field), Header(String, Field), } + +impl ResponseField { + fn is_body(&self) -> bool { + match *self { + ResponseField::Body(_) => true, + _ => false, + } + } +}