Add transform = ... attribute (#312)

This allows running arbitrary transforms on generated schemas when deriving `JsonSchema`
This commit is contained in:
Graham Esau 2024-08-10 09:56:52 +01:00 committed by GitHub
parent 29067a0331
commit 14b06e71ba
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 173 additions and 10 deletions

View file

@ -1,4 +1,5 @@
use proc_macro2::TokenStream;
use syn::spanned::Spanned;
#[derive(Debug, Clone)]
pub struct SchemaMetadata<'a> {
@ -10,6 +11,7 @@ pub struct SchemaMetadata<'a> {
pub examples: &'a [syn::Path],
pub default: Option<TokenStream>,
pub extensions: &'a [(String, TokenStream)],
pub transforms: &'a [syn::Expr],
}
impl<'a> SchemaMetadata<'a> {
@ -23,6 +25,18 @@ impl<'a> SchemaMetadata<'a> {
schema
}}
}
if !self.transforms.is_empty() {
let apply_transforms = self.transforms.iter().map(|t| {
quote_spanned! {t.span()=>
schemars::transform::Transform::transform(&mut #t, &mut schema);
}
});
*schema_expr = quote! {{
let mut schema = #schema_expr;
#(#apply_transforms)*
schema
}};
}
}
fn make_setters(&self) -> Vec<TokenStream> {