added the traits to the crate and made proc macros compatible
This commit is contained in:
58
src/lib.rs
58
src/lib.rs
@ -2,12 +2,27 @@ use proc_macro::TokenStream;
|
|||||||
use quote::quote;
|
use quote::quote;
|
||||||
use syn::{parse_macro_input, ItemEnum, Lit, DeriveInput, Fields, Data};
|
use syn::{parse_macro_input, ItemEnum, Lit, DeriveInput, Fields, Data};
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
pub trait Queryable {
|
||||||
|
///send the query types query and get the response returned as the
|
||||||
|
///proper response type
|
||||||
|
pub fn send(
|
||||||
|
&self,
|
||||||
|
base_url: &str,
|
||||||
|
headers: Option<Vec<(&str, &str)>>,
|
||||||
|
) -> Result<Response, std::io::Error>;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait Responsable {
|
||||||
|
pub fn receive(resp: Response) -> Result<Self, std::error::Error>;
|
||||||
|
}
|
||||||
|
|
||||||
#[proc_macro_derive(HttpRequest, attributes(http_get))]
|
#[proc_macro_derive(HttpRequest, attributes(http_get))]
|
||||||
pub fn derive_http_get_request(input: TokenStream) -> TokenStream {
|
pub fn derive_http_get_request(input: TokenStream) -> TokenStream {
|
||||||
let input = parse_macro_input!(input as DeriveInput);
|
let input = parse_macro_input!(input as DeriveInput);
|
||||||
let name = &input.ident;
|
let name = &input.ident;
|
||||||
|
|
||||||
// Parse #[http_get(url = "...")] attribute
|
// Extract the base URL from #[http_get(url = "...")]
|
||||||
let mut base_url = None;
|
let mut base_url = None;
|
||||||
for attr in &input.attrs {
|
for attr in &input.attrs {
|
||||||
if attr.path().is_ident("http_get") {
|
if attr.path().is_ident("http_get") {
|
||||||
@ -22,7 +37,6 @@ pub fn derive_http_get_request(input: TokenStream) -> TokenStream {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let base_url = base_url.expect("Missing #[http_get(url = \"...\")] attribute");
|
let base_url = base_url.expect("Missing #[http_get(url = \"...\")] attribute");
|
||||||
|
|
||||||
let expanded = match &input.data {
|
let expanded = match &input.data {
|
||||||
@ -46,22 +60,18 @@ pub fn derive_http_get_request(input: TokenStream) -> TokenStream {
|
|||||||
|
|
||||||
quote! {
|
quote! {
|
||||||
impl Queryable for #name {
|
impl Queryable for #name {
|
||||||
pub async fn send(
|
fn send(
|
||||||
&self,
|
&self,
|
||||||
client: std::sync::Arc<awc::Client>,
|
base_url: &str,
|
||||||
headers: Option<Vec<(&str, &str)>>,
|
headers: Option<Vec<(&str, &str)>>,
|
||||||
api_key: Option<&str>,
|
) -> Result<Response, std::io::Error> {
|
||||||
) -> Result<awc::ClientResponse, actix_web::error::SendRequestError> {
|
|
||||||
use urlencoding::encode;
|
use urlencoding::encode;
|
||||||
|
use awc::Client;
|
||||||
|
|
||||||
let mut query_params: Vec<(String, String)> = Vec::new();
|
let mut query_params: Vec<(String, String)> = Vec::new();
|
||||||
#(#query_param_code)*
|
#(#query_param_code)*
|
||||||
|
|
||||||
if let Some(key) = api_key {
|
let mut url = base_url.to_string();
|
||||||
query_params.push(("api_key".to_string(), key.to_string()));
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut url = #base_url.to_string();
|
|
||||||
if !query_params.is_empty() {
|
if !query_params.is_empty() {
|
||||||
let query_parts: Vec<String> = query_params.iter()
|
let query_parts: Vec<String> = query_params.iter()
|
||||||
.map(|(k, v)| format!("{}={}", k, encode(v)))
|
.map(|(k, v)| format!("{}={}", k, encode(v)))
|
||||||
@ -70,6 +80,7 @@ pub fn derive_http_get_request(input: TokenStream) -> TokenStream {
|
|||||||
url.push_str(&query_parts.join("&"));
|
url.push_str(&query_parts.join("&"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let client = Client::default();
|
||||||
let mut request = client.get(url);
|
let mut request = client.get(url);
|
||||||
|
|
||||||
if let Some(hdrs) = headers {
|
if let Some(hdrs) = headers {
|
||||||
@ -78,8 +89,18 @@ pub fn derive_http_get_request(input: TokenStream) -> TokenStream {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let response = request.send().await?;
|
let response = actix_web::rt::System::new()
|
||||||
Ok(response)
|
.block_on(async { request.send().await })
|
||||||
|
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.to_string()))?;
|
||||||
|
|
||||||
|
let body_bytes = actix_web::rt::System::new()
|
||||||
|
.block_on(async { response.body().await })
|
||||||
|
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.to_string()))?;
|
||||||
|
|
||||||
|
let body = Response::receive(body_bytes.to_vec())
|
||||||
|
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.to_string()))?;
|
||||||
|
|
||||||
|
Ok(body)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -92,7 +113,7 @@ pub fn derive_http_get_request(input: TokenStream) -> TokenStream {
|
|||||||
match &variant.fields {
|
match &variant.fields {
|
||||||
Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
|
Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
|
||||||
variant_arms.push(quote! {
|
variant_arms.push(quote! {
|
||||||
#name::#vname(inner) => inner.send(client.clone(), headers.clone(), api_key).await,
|
#name::#vname(inner) => inner.send(base_url, headers.clone()),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
_ => panic!("#[derive(HttpRequest)] enum variants must have a single unnamed field"),
|
_ => panic!("#[derive(HttpRequest)] enum variants must have a single unnamed field"),
|
||||||
@ -100,13 +121,12 @@ pub fn derive_http_get_request(input: TokenStream) -> TokenStream {
|
|||||||
}
|
}
|
||||||
|
|
||||||
quote! {
|
quote! {
|
||||||
impl #name {
|
impl Queryable for #name {
|
||||||
pub async fn send(
|
fn send(
|
||||||
&self,
|
&self,
|
||||||
client: std::sync::Arc<awc::Client>,
|
base_url: &str,
|
||||||
headers: Option<Vec<(&str, &str)>>,
|
headers: Option<Vec<(&str, &str)>>,
|
||||||
api_key: Option<&str>,
|
) -> Result<Response, std::io::Error> {
|
||||||
) -> Result<awc::ClientResponse, actix_web::error::SendRequestError> {
|
|
||||||
match self {
|
match self {
|
||||||
#(#variant_arms)*
|
#(#variant_arms)*
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user