Skip to main content

navree_openapi/
component.rs

1//! [`ComponentProperties`]: properties a module adds to a component schema.
2
3use std::borrow::Cow;
4use std::collections::BTreeMap;
5
6use crate::Schema;
7
8/// Properties a module adds at run time to the values of one component
9/// schema, so the OpenAPI document lists them too. navree-auth's user
10/// resource extensions add fields to `UserResource` this way (an app's
11/// `roles`, say).
12///
13/// A module contributes it (`ModuleBuilder::contribute`), and navree-api
14/// [applies](Self::apply) every one to the document's components: each
15/// property goes after the type's own, and one of the same name replaces the
16/// type's, as an extension may overwrite a field. A document without the
17/// component is left as it is.
18#[derive(Clone, Debug)]
19pub struct ComponentProperties {
20    /// The component's name (`UserResource`).
21    pub component: Cow<'static, str>,
22    /// Each property's name and schema, and whether every value has it.
23    pub properties: fn() -> Vec<(String, Schema, bool)>,
24}
25
26impl ComponentProperties {
27    /// Adds the properties to the schema named [`component`](Self::component)
28    /// in `components`, when there is one.
29    pub fn apply(&self, components: &mut BTreeMap<String, Schema>) {
30        let Some(schema) = components.get_mut(self.component.as_ref()) else {
31            return;
32        };
33        for (name, property, required) in (self.properties)() {
34            if required && !schema.required.contains(&name) {
35                schema.required.push(name.clone());
36            }
37            schema.properties.insert(name, property);
38        }
39    }
40}
41
42#[cfg(test)]
43mod tests {
44    use serde_json::json;
45
46    use super::*;
47
48    fn roles() -> Vec<(String, Schema, bool)> {
49        vec![
50            ("roles".to_owned(), Schema::array(Schema::string()), true),
51            (
52                "name".to_owned(),
53                Schema::string().description("Shown."),
54                false,
55            ),
56        ]
57    }
58
59    #[test]
60    fn properties_join_the_component_and_replace_one_of_the_same_name() {
61        let mut components = BTreeMap::from([(
62            "UserResource".to_owned(),
63            Schema::object()
64                .property("id", Schema::string(), true)
65                .property("name", Schema::string(), true),
66        )]);
67        let extension = ComponentProperties {
68            component: Cow::Borrowed("UserResource"),
69            properties: roles,
70        };
71        extension.apply(&mut components);
72        let schema = serde_json::to_value(&components["UserResource"]).unwrap();
73        assert_eq!(schema["required"], json!(["id", "name", "roles"]));
74        assert_eq!(schema["properties"]["roles"]["items"]["type"], "string");
75        assert_eq!(schema["properties"]["name"]["description"], "Shown.");
76        let names: Vec<&String> = components["UserResource"].properties.keys().collect();
77        assert_eq!(names, ["id", "name", "roles"]);
78        // Applying again changes nothing.
79        extension.apply(&mut components);
80        assert_eq!(
81            serde_json::to_value(&components["UserResource"]).unwrap(),
82            schema
83        );
84    }
85
86    #[test]
87    fn a_document_without_the_component_is_left_alone() {
88        let mut components = BTreeMap::from([("Deal".to_owned(), Schema::object())]);
89        ComponentProperties {
90            component: Cow::Borrowed("UserResource"),
91            properties: roles,
92        }
93        .apply(&mut components);
94        assert_eq!(components.len(), 1);
95        assert!(components["Deal"].properties.is_empty());
96    }
97}