schemars_derive/
metadata.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
use proc_macro2::TokenStream;

#[derive(Debug, Clone)]
pub struct SchemaMetadata<'a> {
    pub title: Option<&'a str>,
    pub description: Option<&'a str>,
    pub deprecated: bool,
    pub read_only: bool,
    pub write_only: bool,
    pub examples: &'a [syn::Path],
    pub default: Option<TokenStream>,
}

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! {
                schemars::_private::apply_metadata(#schema_expr, schemars::schema::Metadata {
                    #(#setters)*
                    ..Default::default()
                })
            }
        }
    }

    fn make_setters(&self) -> Vec<TokenStream> {
        let mut setters = Vec::<TokenStream>::new();

        if let Some(title) = &self.title {
            setters.push(quote! {
                title: Some(#title.to_owned()),
            });
        }
        if let Some(description) = &self.description {
            setters.push(quote! {
                description: Some(#description.to_owned()),
            });
        }

        if self.deprecated {
            setters.push(quote! {
                deprecated: true,
            });
        }

        if self.read_only {
            setters.push(quote! {
                read_only: true,
            });
        }
        if self.write_only {
            setters.push(quote! {
                write_only: true,
            });
        }

        if !self.examples.is_empty() {
            let examples = self.examples.iter().map(|eg| {
                quote! {
                    schemars::_serde_json::value::to_value(#eg())
                }
            });
            setters.push(quote! {
                examples: vec![#(#examples),*].into_iter().flatten().collect(),
            });
        }

        if let Some(default) = &self.default {
            setters.push(quote! {
                default: #default.and_then(|d| schemars::_schemars_maybe_to_value!(d)),
            });
        }

        setters
    }
}