navree_openapi/
component.rs1use std::borrow::Cow;
4use std::collections::BTreeMap;
5
6use crate::Schema;
7
8#[derive(Clone, Debug)]
19pub struct ComponentProperties {
20 pub component: Cow<'static, str>,
22 pub properties: fn() -> Vec<(String, Schema, bool)>,
24}
25
26impl ComponentProperties {
27 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 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}