Skip to main content

navree_openapi/
to_schema.rs

1//! [`ToSchema`] and its implementations for the types of the standard library,
2//! chrono, uuid and serde_json.
3
4use std::borrow::{Cow, ToOwned};
5use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
6use std::rc::Rc;
7use std::sync::Arc;
8
9use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime, TimeZone};
10use serde_json::{Value, json};
11use uuid::Uuid;
12
13use crate::{Schema, Type};
14
15/// A type described by a JSON Schema: `#[derive(ToSchema)]`, or by hand.
16///
17/// The derive reads the type's serde attributes, so the schema matches the JSON
18/// serde reads and writes, and `#[schema(..)]` for what serde doesn't say.
19/// Written by hand, [`schema`](ToSchema::schema) is the only method a type
20/// needs:
21///
22/// ```
23/// use navree_openapi::{Schema, ToSchema};
24///
25/// struct Zone(String);
26///
27/// impl ToSchema for Zone {
28///     fn schema() -> Schema {
29///         Schema::string().description("An IANA time zone name.")
30///     }
31/// }
32///
33/// assert_eq!(Zone::name(), "Zone");
34/// ```
35pub trait ToSchema {
36    /// The name of the type's component schema: the last segment of its Rust
37    /// path unless `#[schema(as = Name)]` says otherwise, followed by the names
38    /// of its generic arguments (`Page<Note>` is `Page_Note`).
39    fn name() -> Cow<'static, str> {
40        let name = std::any::type_name::<Self>();
41        let name = name.split('<').next().unwrap_or(name);
42        Cow::Borrowed(name.rsplit("::").next().unwrap_or(name))
43    }
44
45    /// The type's schema.
46    fn schema() -> Schema;
47
48    /// What a field or an element of this type says: a `$ref` to the component,
49    /// or for a type with no component of its own (`String`, `Vec<T>`) its
50    /// schema.
51    fn reference() -> Schema {
52        Schema::reference_to(&Self::name())
53    }
54
55    /// Adds the component schemas [`schema`](ToSchema::schema) refers to.
56    fn schemas(out: &mut Vec<(String, Schema)>) {
57        let _ = out;
58    }
59
60    /// Adds the component schemas [`reference`](ToSchema::reference) refers to:
61    /// this type's and what it refers to. A type already in `out` isn't walked
62    /// again, so a type that contains itself ends. Another type of the same name
63    /// is walked as well, even with the same schema, since what its `$ref`s mean
64    /// may differ: a different schema of one name goes in beside the first, for
65    /// the document to refuse.
66    fn components(out: &mut Vec<(String, Schema)>) {
67        let name = Self::name();
68        let rust_type = std::any::type_name::<Self>();
69        let schema = Schema {
70            rust_type: crate::schema::RustType(Some(rust_type)),
71            ..Self::schema()
72        };
73        let walked = out
74            .iter()
75            .any(|(existing, other)| *existing == name && other.rust_type.0 == Some(rust_type));
76        if walked {
77            let same = out
78                .iter()
79                .any(|(existing, other)| *existing == name && *other == schema);
80            if !same {
81                out.push((name.into_owned(), schema));
82            }
83            return;
84        }
85        out.push((name.into_owned(), schema));
86        Self::schemas(out);
87    }
88}
89
90/// The component schemas `T` refers to, one for each name: what a schema that
91/// stands alone puts under `$defs`.
92///
93/// # Panics
94///
95/// When two different schemas have one name, since a `$ref` could only mean one
96/// of them and a tool's caller or a model would be told the wrong shape. The
97/// message names both types; `#[schema(as = Name)]` renames one.
98///
99/// ```
100/// use navree_openapi::{ToSchema, components_of};
101///
102/// #[derive(ToSchema)]
103/// #[allow(dead_code)]
104/// struct Stage {
105///     name: String,
106/// }
107///
108/// #[derive(ToSchema)]
109/// #[allow(dead_code)]
110/// struct Deal {
111///     stage: Stage,
112/// }
113///
114/// assert!(components_of::<Deal>().contains_key("Stage"));
115/// ```
116pub fn components_of<T: ToSchema + ?Sized>() -> BTreeMap<String, Schema> {
117    let mut referenced = Vec::new();
118    T::schemas(&mut referenced);
119    let mut components: BTreeMap<String, Schema> = BTreeMap::new();
120    for (name, schema) in referenced {
121        match components.get(&name) {
122            Some(first) if *first == schema => {}
123            Some(first) => panic!(
124                "`{name}` names two different schemas under `{}`: `{}` and `{}`; give one of them another name with #[schema(as = Name)]",
125                std::any::type_name::<T>(),
126                first.rust_type.0.unwrap_or("a schema written by hand"),
127                schema.rust_type.0.unwrap_or("a schema written by hand"),
128            ),
129            None => {
130                components.insert(name, schema);
131            }
132        }
133    }
134    components
135}
136
137/// `#[schema(value_type = Object)]`: `{"type": "object"}`, whatever the field's
138/// Rust type is.
139#[derive(Clone, Copy, Debug)]
140pub struct Object;
141
142/// A type with no component: fields inline its schema.
143macro_rules! inline_schema {
144    ($(impl[$($generics:tt)*] $ty:ty => $schema:expr;)+) => {$(
145        impl<$($generics)*> ToSchema for $ty {
146            fn schema() -> Schema {
147                $schema
148            }
149
150            fn reference() -> Schema {
151                Self::schema()
152            }
153
154            fn components(_out: &mut Vec<(String, Schema)>) {}
155        }
156    )+};
157}
158
159fn integer(format: Option<&str>, unsigned: bool) -> Schema {
160    Schema {
161        format: format.map(str::to_owned),
162        minimum: unsigned.then(|| json!(0)),
163        ..Schema::of_type(Type::Integer)
164    }
165}
166
167fn number(format: &str) -> Schema {
168    Schema {
169        format: Some(format.to_owned()),
170        ..Schema::of_type(Type::Number)
171    }
172}
173
174fn formatted(format: &str) -> Schema {
175    Schema {
176        format: Some(format.to_owned()),
177        ..Schema::string()
178    }
179}
180
181inline_schema! {
182    impl[] String => Schema::string();
183    impl[] str => Schema::string();
184    impl[] char => Schema::string();
185    impl[] bool => Schema::of_type(Type::Boolean);
186    impl[] i8 => integer(Some("int32"), false);
187    impl[] i16 => integer(Some("int32"), false);
188    impl[] i32 => integer(Some("int32"), false);
189    impl[] i64 => integer(Some("int64"), false);
190    impl[] i128 => integer(None, false);
191    impl[] isize => integer(None, false);
192    impl[] u8 => integer(Some("int32"), true);
193    impl[] u16 => integer(Some("int32"), true);
194    impl[] u32 => integer(Some("int32"), true);
195    impl[] u64 => integer(Some("int64"), true);
196    impl[] u128 => integer(None, true);
197    impl[] usize => integer(None, true);
198    impl[] f32 => number("float");
199    impl[] f64 => number("double");
200    impl[] Uuid => formatted("uuid");
201    impl[Tz: TimeZone] DateTime<Tz> => formatted("date-time");
202    impl[] NaiveDateTime => formatted("date-time");
203    impl[] NaiveDate => formatted("date");
204    impl[] NaiveTime => Schema::string();
205    impl[] Value => Schema::default();
206    impl[] serde_json::Map<String, Value> => Schema::map(Schema::string(), Schema::default());
207    impl[] Object => Schema::object();
208}
209
210impl ToSchema for () {
211    fn name() -> Cow<'static, str> {
212        Cow::Borrowed("TupleUnit")
213    }
214
215    fn schema() -> Schema {
216        Schema::default().default_value(Value::Null)
217    }
218
219    fn reference() -> Schema {
220        Self::schema()
221    }
222
223    fn components(_out: &mut Vec<(String, Schema)>) {}
224}
225
226/// A wrapper that serializes as `T`: its schema and what it refers to are `T`'s.
227macro_rules! transparent {
228    ($(impl[$($generics:tt)*] $ty:ty => $inner:ty;)+) => {$(
229        impl<$($generics)*> ToSchema for $ty {
230            fn name() -> Cow<'static, str> {
231                <$inner>::name()
232            }
233
234            fn schema() -> Schema {
235                <$inner>::schema()
236            }
237
238            fn reference() -> Schema {
239                <$inner>::reference()
240            }
241
242            fn schemas(out: &mut Vec<(String, Schema)>) {
243                <$inner>::schemas(out);
244            }
245
246            fn components(out: &mut Vec<(String, Schema)>) {
247                <$inner>::components(out);
248            }
249        }
250    )+};
251}
252
253transparent! {
254    impl[T: ToSchema + ?Sized] Box<T> => T;
255    impl[T: ToSchema + ?Sized] Rc<T> => T;
256    impl[T: ToSchema + ?Sized] Arc<T> => T;
257    impl['a, T: ToSchema + ToOwned + ?Sized] Cow<'a, T> => T;
258}
259
260/// A reference is the referent's.
261macro_rules! reference {
262    ($(impl[$($generics:tt)*] $ty:ty;)+) => {$(
263        impl<$($generics)*> ToSchema for $ty {
264            fn name() -> Cow<'static, str> {
265                T::name()
266            }
267
268            fn schema() -> Schema {
269                T::schema()
270            }
271
272            fn reference() -> Schema {
273                T::reference()
274            }
275
276            fn schemas(out: &mut Vec<(String, Schema)>) {
277                T::schemas(out);
278            }
279
280            fn components(out: &mut Vec<(String, Schema)>) {
281                T::components(out);
282            }
283        }
284    )+};
285}
286
287reference! {
288    impl['a, T: ToSchema + ?Sized] &'a T;
289    impl['a, T: ToSchema + ?Sized] &'a mut T;
290}
291
292/// `Option<T>` on its own is `{"oneOf": [{"type": "null"}, T's schema]}`; as a
293/// field it's what `T` says, nullable.
294impl<T: ToSchema> ToSchema for Option<T> {
295    fn name() -> Cow<'static, str> {
296        Cow::Owned(format!("Option_{}", T::name()))
297    }
298
299    fn schema() -> Schema {
300        Schema::one_of(vec![Schema::null(), T::schema()])
301    }
302
303    fn reference() -> Schema {
304        T::reference().nullable()
305    }
306
307    fn schemas(out: &mut Vec<(String, Schema)>) {
308        T::schemas(out);
309    }
310
311    fn components(out: &mut Vec<(String, Schema)>) {
312        T::components(out);
313    }
314}
315
316/// A list: `{"type": "array", "items": ..}`, with `T`'s schema on its own and
317/// what `T` says as a field.
318macro_rules! list {
319    ($(impl[$($generics:tt)*] $ty:ty => $unique:expr;)+) => {$(
320        impl<$($generics)*> ToSchema for $ty {
321            fn name() -> Cow<'static, str> {
322                let list = if ($unique as Option<bool>).is_some() { "Set" } else { "Vec" };
323                Cow::Owned(format!("{list}_{}", T::name()))
324            }
325
326            fn schema() -> Schema {
327                Schema {
328                    unique_items: $unique,
329                    ..Schema::array(T::schema())
330                }
331            }
332
333            fn reference() -> Schema {
334                Schema {
335                    unique_items: $unique,
336                    ..Schema::array(T::reference())
337                }
338            }
339
340            fn schemas(out: &mut Vec<(String, Schema)>) {
341                T::schemas(out);
342            }
343
344            fn components(out: &mut Vec<(String, Schema)>) {
345                T::components(out);
346            }
347        }
348    )+};
349}
350
351list! {
352    impl[T: ToSchema] Vec<T> => None;
353    impl[T: ToSchema] [T] => None;
354    impl[T: ToSchema, const N: usize] [T; N] => None;
355    impl[T: ToSchema] std::collections::LinkedList<T> => None;
356    impl[T: ToSchema] std::collections::VecDeque<T> => None;
357    impl[T: ToSchema, S] HashSet<T, S> => Some(true);
358    impl[T: ToSchema] BTreeSet<T> => Some(true);
359}
360
361/// A map: `{"type": "object", "additionalProperties": .., "propertyNames": ..}`,
362/// with `V`'s schema on its own and what `V` says as a field.
363macro_rules! map {
364    ($(impl[$($generics:tt)*] $ty:ty;)+) => {$(
365        impl<$($generics)*> ToSchema for $ty {
366            fn name() -> Cow<'static, str> {
367                Cow::Owned(format!("Map_{}_{}", K::name(), V::name()))
368            }
369
370            fn schema() -> Schema {
371                Schema::map(K::schema(), V::schema())
372            }
373
374            fn reference() -> Schema {
375                Schema::map(K::reference(), V::reference())
376            }
377
378            fn schemas(out: &mut Vec<(String, Schema)>) {
379                K::schemas(out);
380                V::schemas(out);
381            }
382
383            fn components(out: &mut Vec<(String, Schema)>) {
384                K::components(out);
385                V::components(out);
386            }
387        }
388    )+};
389}
390
391map! {
392    impl[K: ToSchema, V: ToSchema] BTreeMap<K, V>;
393    impl[K: ToSchema, V: ToSchema, S] HashMap<K, V, S>;
394    impl[K: ToSchema, V: ToSchema, S] indexmap::IndexMap<K, V, S>;
395}
396
397#[cfg(test)]
398mod tests {
399    use serde_json::json;
400
401    use super::*;
402
403    struct Deal;
404
405    impl ToSchema for Deal {
406        fn schema() -> Schema {
407            Schema::object()
408        }
409    }
410
411    fn value<T: ToSchema + ?Sized>() -> Value {
412        T::reference().to_value()
413    }
414
415    #[test]
416    fn primitives_are_inline() {
417        assert_eq!(value::<String>(), json!({"type": "string"}));
418        assert_eq!(value::<&'static str>(), json!({"type": "string"}));
419        assert_eq!(value::<Cow<'static, str>>(), json!({"type": "string"}));
420        assert_eq!(
421            value::<u64>(),
422            json!({"type": "integer", "format": "int64", "minimum": 0})
423        );
424        assert_eq!(
425            value::<i32>(),
426            json!({"type": "integer", "format": "int32"})
427        );
428        assert_eq!(value::<usize>(), json!({"type": "integer", "minimum": 0}));
429        assert_eq!(
430            value::<f64>(),
431            json!({"type": "number", "format": "double"})
432        );
433        assert_eq!(value::<Uuid>(), json!({"type": "string", "format": "uuid"}));
434        assert_eq!(
435            value::<DateTime<chrono::Utc>>(),
436            json!({"type": "string", "format": "date-time"})
437        );
438        assert_eq!(value::<Value>(), json!({}));
439    }
440
441    #[test]
442    fn options_are_nullable() {
443        assert_eq!(
444            value::<Option<bool>>(),
445            json!({"type": ["boolean", "null"]})
446        );
447        assert_eq!(
448            value::<Option<Option<String>>>(),
449            json!({"type": ["string", "null"]})
450        );
451        assert_eq!(
452            value::<Option<Deal>>(),
453            json!({"oneOf": [{"$ref": "#/components/schemas/Deal"}, {"type": "null"}]})
454        );
455        assert_eq!(value::<Option<Value>>(), json!({}));
456    }
457
458    #[test]
459    fn lists_and_maps_compose() {
460        assert_eq!(
461            value::<Vec<Deal>>(),
462            json!({"type": "array", "items": {"$ref": "#/components/schemas/Deal"}})
463        );
464        assert_eq!(
465            value::<BTreeSet<String>>(),
466            json!({"type": "array", "items": {"type": "string"}, "uniqueItems": true})
467        );
468        assert_eq!(
469            value::<BTreeMap<String, Deal>>(),
470            json!({
471                "type": "object",
472                "additionalProperties": {"$ref": "#/components/schemas/Deal"},
473                "propertyNames": {"type": "string"},
474            })
475        );
476    }
477
478    #[test]
479    fn components_reach_through_wrappers_and_stop_at_primitives() {
480        let mut out = Vec::new();
481        <Option<Vec<BTreeMap<String, Box<Deal>>>>>::components(&mut out);
482        assert_eq!(out.len(), 1);
483        assert_eq!(out[0].0, "Deal");
484        let mut out = Vec::new();
485        <Vec<String>>::components(&mut out);
486        assert!(out.is_empty());
487    }
488
489    #[test]
490    fn a_type_containing_itself_ends() {
491        struct Tree;
492        impl ToSchema for Tree {
493            fn schema() -> Schema {
494                Schema::object().property("children", <Vec<Tree>>::reference(), true)
495            }
496            fn schemas(out: &mut Vec<(String, Schema)>) {
497                <Vec<Tree>>::components(out);
498            }
499        }
500        let mut out = Vec::new();
501        Tree::components(&mut out);
502        assert_eq!(out.len(), 1);
503    }
504}