Define Schema as a newtype around serde_json::Value (#289)

This commit is contained in:
Graham Esau 2024-05-12 19:23:54 +01:00 committed by GitHub
parent 7f6a7b7e32
commit 342cd5fd09
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
79 changed files with 1410 additions and 2394 deletions

View file

@ -13,32 +13,46 @@ pub struct SchemaMetadata<'a> {
impl<'a> SchemaMetadata<'a> {
pub fn apply_to_schema(&self, schema_expr: &mut TokenStream) {
let setters = self.make_setters();
if !setters.is_empty() {
*schema_expr = quote! {{
let mut schema = #schema_expr;
let obj = schema.ensure_object();
#(#setters)*
schema
}}
}
}
fn make_setters(&self) -> Vec<TokenStream> {
let mut setters = Vec::<TokenStream>::new();
if let Some(title) = &self.title {
*schema_expr = quote! {
schemars::_private::metadata::add_title(#schema_expr, #title)
};
setters.push(quote! {
obj.insert("title".to_owned(), #title.into());
});
}
if let Some(description) = &self.description {
*schema_expr = quote! {
schemars::_private::metadata::add_description(#schema_expr, #description)
};
setters.push(quote! {
obj.insert("description".to_owned(), #description.into());
});
}
if self.deprecated {
*schema_expr = quote! {
schemars::_private::metadata::add_deprecated(#schema_expr, true)
};
setters.push(quote! {
obj.insert("deprecated".to_owned(), true.into());
});
}
if self.read_only {
*schema_expr = quote! {
schemars::_private::metadata::add_read_only(#schema_expr, true)
};
setters.push(quote! {
obj.insert("readOnly".to_owned(), true.into());
});
}
if self.write_only {
*schema_expr = quote! {
schemars::_private::metadata::add_write_only(#schema_expr, true)
};
setters.push(quote! {
obj.insert("writeOnly".to_owned(), true.into());
});
}
if !self.examples.is_empty() {
@ -47,16 +61,19 @@ impl<'a> SchemaMetadata<'a> {
schemars::_serde_json::value::to_value(#eg())
}
});
*schema_expr = quote! {
schemars::_private::metadata::add_examples(#schema_expr, [#(#examples),*].into_iter().flatten())
};
setters.push(quote! {
obj.insert("examples".to_owned(), schemars::_serde_json::Value::Array([#(#examples),*].into_iter().flatten().collect()));
});
}
if let Some(default) = &self.default {
*schema_expr = quote! {
schemars::_private::metadata::add_default(#schema_expr, #default.and_then(|d| schemars::_schemars_maybe_to_value!(d)))
};
setters.push(quote! {
if let Some(default) = #default.and_then(|d| schemars::_schemars_maybe_to_value!(d)) {
obj.insert("default".to_owned(), default);
}
});
}
setters
}
}