Skip to main content

schematools/codegen/jsonschema/
required.rs

1use crate::scope::SchemaScope;
2use serde_json::Map;
3use serde_json::Value;
4
5pub fn extract_required(data: &Map<String, Value>, scope: &SchemaScope) -> Vec<String> {
6    match data.get("required").unwrap_or(&serde_json::json!([])) {
7        Value::Array(a) => a.iter().map(|v| v.as_str().unwrap().to_string()).collect(),
8        _ => {
9            log::error!("{}: Incorrect format of required", scope);
10            vec![]
11        }
12    }
13}
14
15#[cfg(test)]
16mod tests {
17    use super::*;
18    use serde_json::json;
19
20    #[test]
21    fn test_required_exists() {
22        let schema = json!({
23            "required": ["a", "b", "c"]
24        });
25
26        let mut scope = SchemaScope::default();
27        let result = extract_required(schema.as_object().unwrap(), &mut scope);
28
29        assert_eq!(
30            result,
31            vec!["a".to_string(), "b".to_string(), "c".to_string()]
32        );
33    }
34
35    #[test]
36    fn test_required_missing() {
37        let schema = json!({});
38
39        let mut scope = SchemaScope::default();
40        let result = extract_required(schema.as_object().unwrap(), &mut scope);
41
42        let expected: Vec<String> = vec![];
43        assert_eq!(result, expected);
44    }
45}