-
Notifications
You must be signed in to change notification settings - Fork 46
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
editoast: derive: add macro to add utoipa schema for units
Signed-off-by: Tristram Gräbener <[email protected]>
- Loading branch information
Showing
2 changed files
with
68 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
use darling::Result; | ||
use proc_macro2::TokenStream; | ||
use quote::quote; | ||
use syn::{parse_quote, DeriveInput, LitStr}; | ||
|
||
pub fn get_abbreviation(value: String) -> Option<&'static str> { | ||
match value.replace("::option", "").as_str() { | ||
"meter" => Some("Length in m"), | ||
"millimeter" => Some("Length in mm"), | ||
"meter_per_second" => Some("Velocity in m·s⁻¹"), | ||
"kilometer_per_hour" => Some("Velocity in km·h⁻¹"), | ||
"meter_per_second_squared" => Some("Acceleration in m·s⁻²"), | ||
_ => None, | ||
} | ||
} | ||
|
||
pub fn annotate_units(input: &mut DeriveInput) -> Result<TokenStream> { | ||
// We look for fields that have #[sered(with="meter")] attributes | ||
// and we push two new attributes to it to improve the OpenAPI | ||
match &mut input.data { | ||
syn::Data::Struct(s) => { | ||
for f in s.fields.iter_mut() { | ||
for attr in f.attrs.clone() { | ||
if attr.path().is_ident("serde") { | ||
let _ = attr.parse_nested_meta(|meta| { | ||
if meta.path.is_ident("with") { | ||
let value = meta.value()?; | ||
let s: LitStr = value.parse()?; | ||
if let Some(abbreviation) = get_abbreviation(s.value()) { | ||
if s.value().ends_with("::option") { | ||
f.attrs.push( | ||
parse_quote! {#[schema(value_type = Option<f64>)]}, | ||
); | ||
} else { | ||
f.attrs.push(parse_quote! {#[schema(value_type = f64)]}); | ||
} | ||
f.attrs.push(parse_quote! {#[doc = #abbreviation]}); | ||
} | ||
} | ||
Ok(()) | ||
}); | ||
} | ||
} | ||
} | ||
} | ||
_ => {} | ||
} | ||
Ok(quote! {#input}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters