schematools/codegen/jsonschema/
title.rs1use crate::{error::Error, scope::SchemaScope};
2use serde_json::{Map, Value};
3
4use super::JsonSchemaExtractOptions;
5
6pub fn extract_title(
7 data: &Map<String, Value>,
8 scope: &mut SchemaScope,
9 _options: &JsonSchemaExtractOptions,
10) -> Result<String, Error> {
11 match data.get("title") {
12 Some(v) => match v {
13 Value::String(title) => Ok(scope.namer().convert(title)),
14 _ => {
15 log::error!("{}: Incorrect format of title", scope);
16
17 Err(Error::SchemaInvalidProperty("title".to_string()))
18 }
19 },
20 None => scope.namer().simple(),
21 }
22}
23
24#[cfg(test)]
25mod tests {
26 use super::*;
27 use serde_json::json;
28
29 #[test]
30 fn test_should_return_title_when_available() {
31 let data = json!({"title": "MyTitle"});
32 let scope = &mut SchemaScope::default();
33
34 let result = extract_title(
35 data.as_object().unwrap(),
36 scope,
37 &JsonSchemaExtractOptions::default(),
38 );
39
40 assert_eq!(result.unwrap(), "MyTitle".to_string());
41 }
42
43 #[test]
44 fn test_should_return_name_from_scope_when_missing() {
45 let data = json!({"type": "string"});
46 let scope = &mut SchemaScope::default();
47 scope.entity("MySecretTitle");
48
49 let result = extract_title(
50 data.as_object().unwrap(),
51 scope,
52 &JsonSchemaExtractOptions::default(),
53 );
54
55 assert_eq!(result.unwrap(), "MySecretTitle".to_string());
56 }
57}