This commit is contained in:
2025-07-03 15:03:18 -04:00
commit c11ce53576
4 changed files with 175 additions and 0 deletions

113
src/lib.rs Normal file
View File

@ -0,0 +1,113 @@
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, Data, DeriveInput, Fields};
/// Derives a `.send()` method for API query structs and enums using `awc::Client`.
///
/// - Structs: sends GET requests using fields prefixed with `lnk_p_` as query parameters.
/// - Enums: delegates `.send()` to inner struct that implements `Queryable`.
#[proc_macro_derive(HttpGetRequest)]
pub fn derive_http_get_request(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = input.ident;
let expanded = match &input.data {
// ---- Struct: Build .send() that builds and sends the GET request
Data::Struct(data_struct) => {
let fields = match &data_struct.fields {
Fields::Named(named) => &named.named,
_ => panic!("#[derive(HttpGetRequest)] supports only named fields for structs"),
};
// Gather query parameters from fields prefixed with lnk_p_
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 #name {
/// Sends a GET request using `awc::Client`.
pub async fn send(
&self,
base_url: &str,
headers: Option<Vec<(&str, &str)>>
) -> Result<awc::ClientResponse, awc::error::SendRequestError> {
use awc::Client;
use urlencoding::encode;
// Collect query parameters
let mut query_params: Vec<(String, String)> = Vec::new();
#(#query_param_code)*
// Build URL with query string
let mut url = base_url.to_string();
if !query_params.is_empty() {
let mut query_parts = Vec::new();
for (k, v) in &query_params {
query_parts.push(format!("{}={}", k, encode(v)));
}
url.push('?');
url.push_str(&query_parts.join("&"));
}
// Prepare client and request
let client = Client::default();
let mut request = client.get(url);
// Optional headers
if let Some(hdrs) = headers {
for (k, v) in hdrs {
request = request.append_header((k, v));
}
}
// Send the request
let response = request.send().await?;
Ok(response)
}
}
}
}
// ---- Enum: Match each variant and call .send() on the inner type
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().await,
});
}
_ => panic!(
"#[derive(HttpGetRequest)] enum variants must have a single unnamed field"
),
}
}
quote! {
impl #name {
/// Calls `.send()` on the wrapped query variant.
pub async fn send(&self) -> Result<awc::ClientResponse, awc::error::SendRequestError> {
match self {
#(#variant_arms)*
}
}
}
}
}
_ => panic!("#[derive(HttpGetRequest)] only supports structs and enums"),
};
TokenStream::from(expanded)
}