Skip to main content

ripress_derive/
lib.rs

1use proc_macro::TokenStream;
2
3/// A derive macro for automatically implementing the `FromParams` trait.
4///
5/// This macro can be applied to structs with named fields to automatically
6/// generate an implementation of `FromParams` that extracts route parameters
7/// and parses them into the struct fields.
8///
9/// # Usage
10///
11/// ```rust,ignore
12/// use ripress::req::route_params::FromParams;
13/// use ripress_derive::FromParams;
14///
15/// #[derive(FromParams)]
16/// struct UserParams {
17///     id: i32,
18///     name: String,
19/// }
20/// ```
21///
22/// This will generate an implementation that extracts `id` and `name` from
23/// the route parameters and parses them into the appropriate types.
24#[proc_macro_derive(FromParams)]
25pub fn from_params_derive(input: TokenStream) -> TokenStream {
26    // Parse the input tokens of the type the macro is applied to
27    let ast = syn::parse_macro_input!(input as syn::DeriveInput);
28
29    let struct_name = &ast.ident;
30
31    // Only support struct with named fields
32    let fields = match ast.data {
33        syn::Data::Struct(ref s) => match &s.fields {
34            syn::Fields::Named(named) => &named.named,
35            _ => {
36                return syn::Error::new_spanned(
37                    struct_name,
38                    "FromParams can only be derived for structs with named fields",
39                )
40                .to_compile_error()
41                .into();
42            }
43        },
44        _ => {
45            return syn::Error::new_spanned(
46                struct_name,
47                "FromParams can only be derived for structs",
48            )
49            .to_compile_error()
50            .into();
51        }
52    };
53
54    // Generate parsing and assignment for each struct field
55    let assigns = fields.iter().filter_map(|f| {
56        f.ident.as_ref().map(|ident| {
57            let ident_str = ident.to_string();
58            quote::quote! {
59                let #ident = p.get(#ident_str)
60                    .ok_or_else(|| format!("Missing route parameter: {}", #ident_str))?
61                    .parse()
62                    .map_err(|e| format!("Failed to parse field '{}': {}", #ident_str, e))?;
63            }
64        })
65    });
66
67    let field_names = fields.iter().filter_map(|f| {
68        f.ident.as_ref().map(|ident| {
69            quote::quote! { #ident }
70        })
71    });
72
73    let expanded = quote::quote! {
74        impl ::ripress::req::route_params::FromParams for #struct_name {
75            fn from_params(p: &::ripress::req::route_params::RouteParams) -> Result<Self, String> {
76                #(#assigns)*
77                Ok(Self {
78                    #(#field_names,)*
79                })
80            }
81        }
82    };
83
84    TokenStream::from(expanded)
85}
86
87/// A derive macro for automatically implementing the `FromJson` trait.
88///
89/// This macro can be applied to structs that implement `Deserialize` from serde
90/// to automatically generate an implementation of `FromJson` that extracts JSON
91/// from the request body and deserializes it.
92///
93/// # Usage
94///
95/// ```rust,ignore
96/// use ripress::req::body::json_data::FromJson;
97/// use ripress_derive::FromJson;
98/// use serde::Deserialize;
99///
100/// #[derive(Deserialize, FromJson)]
101/// struct UserData {
102///     name: String,
103///     email: String,
104/// }
105/// ```
106///
107/// This will generate an implementation that extracts JSON from the request body
108/// and deserializes it into the struct. The struct must also derive `Deserialize`
109/// from serde.
110#[proc_macro_derive(FromJson)]
111pub fn from_json_derive(input: TokenStream) -> TokenStream {
112    // Parse the input tokens of the type the macro is applied to
113    let ast = syn::parse_macro_input!(input as syn::DeriveInput);
114
115    let struct_name = &ast.ident;
116
117    let expanded = quote::quote! {
118        impl ::ripress::req::body::json_data::FromJson for #struct_name {
119            fn from_json(data: &::ripress::req::body::RequestBody) -> Result<Self, String> {
120                if let ::ripress::req::body::RequestBody::JSON(json_value) = data {
121                    serde_json::from_value::<Self>(json_value.to_owned())
122                        .map_err(|e| format!("Failed to deserialize JSON: {}", e))
123                } else {
124                    Err("Request body is not JSON".to_string())
125                }
126            }
127        }
128    };
129
130    TokenStream::from(expanded)
131}
132
133/// A derive macro for automatically implementing the `FromData` trait.
134///
135/// This macro can be applied to structs with named fields where each field is expected
136/// to have a corresponding key in the request data, and the value is parsed
137/// from the raw request data as a string.
138///
139/// # Usage
140///
141/// ```rust,ignore
142/// use ripress::req::request_data::FromData;
143/// use ripress_derive::FromData;
144///
145/// #[derive(FromData)]
146/// struct Token {
147///     token: String,
148/// }
149/// ```
150///
151/// This will generate an implementation of `FromData` where each field is expected to exist
152/// in the incoming request data map and is parsed using that field's type's `FromStr`.
153#[proc_macro_derive(FromData)]
154pub fn from_data_derive(input: TokenStream) -> TokenStream {
155    let ast = syn::parse_macro_input!(input as syn::DeriveInput);
156
157    let struct_name = &ast.ident;
158
159    let fields = match ast.data {
160        syn::Data::Struct(ref s) => match &s.fields {
161            syn::Fields::Named(named) => &named.named,
162            _ => {
163                return syn::Error::new_spanned(
164                    struct_name,
165                    "FromData can only be derived for structs with named fields",
166                )
167                .to_compile_error()
168                .into();
169            }
170        },
171        _ => {
172            return syn::Error::new_spanned(
173                struct_name,
174                "FromData can only be derived for structs",
175            )
176            .to_compile_error()
177            .into();
178        }
179    };
180
181    let assigns = fields.iter().filter_map(|f| {
182        f.ident.as_ref().map(|ident| {
183            let ident_str = ident.to_string();
184            quote::quote! {
185                let #ident = data.get(#ident_str)
186                    .ok_or_else(|| format!("Missing request data field: {}", #ident_str))?
187                    .parse()
188                    .map_err(|e| format!("Failed to parse field '{}': {}", #ident_str, e))?;
189            }
190        })
191    });
192
193    let field_names = fields.iter().filter_map(|f| {
194        f.ident.as_ref().map(|ident| {
195            quote::quote! { #ident }
196        })
197    });
198
199    let expanded = quote::quote! {
200        impl ::ripress::req::request_data::FromData for #struct_name {
201            fn from_data(data: &::ripress::req::request_data::RequestData) -> Result<Self, String> {
202                #(#assigns)*
203                Ok(Self {
204                    #(#field_names,)*
205                })
206            }
207        }
208    };
209
210    TokenStream::from(expanded)
211}
212
213#[proc_macro_derive(FromQueryParam)]
214pub fn from_query_param_derive(input: TokenStream) -> TokenStream {
215    let ast = syn::parse_macro_input!(input as syn::DeriveInput);
216
217    let struct_name = &ast.ident;
218
219    let fields = match ast.data {
220        syn::Data::Struct(ref s) => match &s.fields {
221            syn::Fields::Named(named) => &named.named,
222            _ => {
223                return syn::Error::new_spanned(
224                    struct_name,
225                    "QueryParam can only be derived for structs with named fields",
226                )
227                .to_compile_error()
228                .into();
229            }
230        },
231        _ => {
232            return syn::Error::new_spanned(
233                struct_name,
234                "QueryParam can only be derived for structs",
235            )
236            .to_compile_error()
237            .into();
238        }
239    };
240
241    let assigns = fields.iter().filter_map(|f| {
242        f.ident.as_ref().map(|ident| {
243            let ident_str = ident.to_string();
244            quote::quote! {
245                let #ident = params.get(#ident_str)
246                    .ok_or_else(|| format!("Missing query param field: {}", #ident_str))?
247                    .parse()
248                    .map_err(|e| format!("Failed to parse field '{}': {}", #ident_str, e))?;
249            }
250        })
251    });
252
253    let field_names = fields.iter().filter_map(|f| {
254        f.ident.as_ref().map(|ident| {
255            quote::quote! { #ident }
256        })
257    });
258
259    let expanded = quote::quote! {
260        impl ::ripress::req::query_params::FromQueryParam for #struct_name {
261            fn from_query_param(params: &::ripress::req::query_params::QueryParams) -> Result<Self, String> {
262                #(#assigns)*
263                Ok(Self {
264                    #(#field_names,)*
265                })
266            }
267        }
268    };
269
270    TokenStream::from(expanded)
271}