json_model/
attribute.rs

1mod array_items;
2mod const_value;
3mod enum_values;
4mod numeric_max;
5mod numeric_min;
6mod object_properties;
7mod pointer_path;
8mod string_max_length;
9mod string_min_length;
10mod string_pattern;
11mod typ;
12
13pub use self::array_items::*;
14pub use self::const_value::*;
15pub use self::enum_values::*;
16pub use self::numeric_max::*;
17pub use self::numeric_min::*;
18pub use self::object_properties::*;
19pub use self::pointer_path::*;
20pub use self::string_max_length::*;
21pub use self::string_min_length::*;
22pub use self::string_pattern::*;
23pub use self::typ::*;
24
25use crate::definition;
26use crate::error::{Error, ValidationError};
27use crate::validator::{DocumentPath, State};
28
29use std::fmt::Debug;
30use std::hash::{Hash, Hasher};
31
32use serde_json;
33
34pub trait Attribute: Debug {
35    fn validate(
36        &self,
37        state: &State,
38        path: Vec<String>, // Path of the input JSON
39        input: &serde_json::Value,
40    ) -> Result<(), ValidationError>;
41}
42
43pub struct AllowedType {
44    typ: definition::Type,
45    required: bool,
46}
47
48impl AllowedType {
49    pub fn new(typ: definition::Type, required: bool) -> Self {
50        AllowedType { typ, required }
51    }
52
53    pub fn typ(&self) -> definition::Type {
54        self.typ.clone()
55    }
56
57    pub fn required(&self) -> bool {
58        self.required
59    }
60}
61
62impl PartialEq for AllowedType {
63    fn eq(&self, other: &AllowedType) -> bool {
64        self.typ == other.typ
65    }
66}
67impl Eq for AllowedType {}
68
69impl Hash for AllowedType {
70    fn hash<H: Hasher>(&self, state: &mut H) {
71        self.typ.hash(state);
72    }
73}
74
75pub fn extract_id(
76    obj: &serde_json::Map<String, serde_json::Value>,
77    path: &mut DocumentPath,
78) -> Result<String, Error> {
79    match obj.get("id") {
80        Some(id) => match id.as_str() {
81            Some(id_str) => Ok(id_str.to_string()),
82            None => {
83                path.add("id");
84                return Err(Error::InvalidValue {
85                    path: path.clone(),
86                    value: id.clone(),
87                });
88            }
89        },
90        None => {
91            return Err(Error::MissingAttribute {
92                path: path.clone(),
93                attr: "id".to_string(),
94            })
95        }
96    }
97}