i think i fixed it from prev commits
This commit is contained in:
124
src/lib.rs
124
src/lib.rs
@ -2,7 +2,129 @@ use proc_macro::TokenStream;
|
||||
use quote::quote;
|
||||
use syn::{parse_macro_input, ItemEnum, DeriveInput, Fields, Data};
|
||||
|
||||
#[proc_macro_derive(HttpRequest, attributes(http_get))]
|
||||
pub fn derive_http_get_request(input: TokenStream) -> TokenStream {
|
||||
let input = parse_macro_input!(input as DeriveInput);
|
||||
let name = &input.ident;
|
||||
|
||||
// Extract the base URL from #[http_get(url = "...")]
|
||||
let mut base_url = None;
|
||||
for attr in &input.attrs {
|
||||
if attr.path().is_ident("http_get") {
|
||||
let _ = attr.parse_nested_meta(|meta| {
|
||||
if meta.path.is_ident("url") {
|
||||
let value: Lit = meta.value()?.parse()?;
|
||||
if let Lit::Str(litstr) = value {
|
||||
base_url = Some(litstr.value());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
}
|
||||
let base_url = base_url.expect("Missing #[http_get(url = \"...\")] attribute");
|
||||
|
||||
let expanded = match &input.data {
|
||||
Data::Struct(data_struct) => {
|
||||
let fields = match &data_struct.fields {
|
||||
Fields::Named(named) => &named.named,
|
||||
_ => panic!("#[derive(HttpRequest)] only supports structs with named fields"),
|
||||
};
|
||||
|
||||
let mut query_param_code = Vec::new();
|
||||
for field in fields {
|
||||
let ident = field.ident.clone().unwrap();
|
||||
let field_name = ident.to_string();
|
||||
if field_name.starts_with("lnk_p_") {
|
||||
let key = &field_name["lnk_p_".len()..];
|
||||
query_param_code.push(quote! {
|
||||
query_params.push((#key.to_string(), self.#ident.to_string()));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
quote! {
|
||||
impl Queryable for #name {
|
||||
fn send(
|
||||
&self,
|
||||
base_url: &str,
|
||||
headers: Option<Vec<(&str, &str)>>,
|
||||
) -> Result<Response, std::io::Error> {
|
||||
use urlencoding::encode;
|
||||
use awc::Client;
|
||||
|
||||
let mut query_params: Vec<(String, String)> = Vec::new();
|
||||
#(#query_param_code)*
|
||||
|
||||
let mut url = base_url.to_string();
|
||||
if !query_params.is_empty() {
|
||||
let query_parts: Vec<String> = query_params.iter()
|
||||
.map(|(k, v)| format!("{}={}", k, encode(v)))
|
||||
.collect();
|
||||
url.push('?');
|
||||
url.push_str(&query_parts.join("&"));
|
||||
}
|
||||
|
||||
let client = Client::default();
|
||||
let mut request = client.get(url);
|
||||
|
||||
if let Some(hdrs) = headers {
|
||||
for (k, v) in hdrs {
|
||||
request = request.append_header((k, v));
|
||||
}
|
||||
}
|
||||
|
||||
let response = actix_web::rt::System::new()
|
||||
.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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Data::Enum(data_enum) => {
|
||||
let mut variant_arms = Vec::new();
|
||||
for variant in &data_enum.variants {
|
||||
let vname = &variant.ident;
|
||||
match &variant.fields {
|
||||
Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
|
||||
variant_arms.push(quote! {
|
||||
#name::#vname(inner) => inner.send(base_url, headers.clone()),
|
||||
});
|
||||
}
|
||||
_ => panic!("#[derive(HttpRequest)] enum variants must have a single unnamed field"),
|
||||
}
|
||||
}
|
||||
|
||||
quote! {
|
||||
impl Queryable for #name {
|
||||
fn send(
|
||||
&self,
|
||||
base_url: &str,
|
||||
headers: Option<Vec<(&str, &str)>>,
|
||||
) -> Result<Response, std::io::Error> {
|
||||
match self {
|
||||
#(#variant_arms)*
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_ => panic!("#[derive(HttpRequest)] only supports structs and enums"),
|
||||
};
|
||||
|
||||
TokenStream::from(expanded)
|
||||
}
|
||||
|
||||
#[proc_macro_attribute]
|
||||
pub fn http_response(_attr: TokenStream, item: TokenStream) -> TokenStream {
|
||||
@ -81,7 +203,7 @@ pub fn derive_response_vec(input: TokenStream) -> TokenStream {
|
||||
let name = &input.ident;
|
||||
|
||||
let expanded = quote! {
|
||||
impl #name {
|
||||
impl Responsable for #name {
|
||||
/// Deserializes all responses sequentially into a Vec<Self>.
|
||||
/// Assumes `Self` implements `DeserializeOwned`.
|
||||
pub async fn response_vec(
|
||||
|
Reference in New Issue
Block a user