json_model/attribute/
typ.rs1use super::{AllowedType, Attribute};
2use crate::definition;
3use crate::error::{Error, ValidationError};
4use crate::validator::{Context, DocumentPath, State};
5
6use std::collections::HashSet;
7
8use serde_json;
9
10#[derive(Debug)]
11pub struct DefinitionType {
12 name: String,
13 typ: definition::Type,
14}
15
16impl DefinitionType {
17 pub fn new(path: DocumentPath, ctx: &Context) -> Result<Self, Error> {
18 let obj = ctx.raw_definition();
19 let typ = definition::Type::new(obj, path.clone())?;
20 Ok(DefinitionType {
21 name: ctx.name(),
22 typ,
23 })
24 }
25
26 pub fn build(
27 _: &mut State,
28 path: DocumentPath,
29 ctx: &Context,
30 ) -> Result<Box<Attribute>, Error> {
31 Ok(Box::new(DefinitionType::new(path, ctx)?))
32 }
33
34 pub fn allowed_types() -> HashSet<AllowedType> {
35 use crate::definition::Type::*;
36 let mut set: HashSet<AllowedType> = HashSet::new();
37 set.insert(AllowedType::new(Null, true));
38 set.insert(AllowedType::new(Boolean, true));
39 set.insert(AllowedType::new(String, true));
40 set.insert(AllowedType::new(Number, true));
41 set.insert(AllowedType::new(Integer, true));
42 set.insert(AllowedType::new(Object, true));
43 set.insert(AllowedType::new(Array, true));
44 set.insert(AllowedType::new(Enum, true));
45 set.insert(AllowedType::new(Const, true));
46 set.insert(AllowedType::new(Pointer, true));
47 set
48 }
49}
50
51impl Attribute for DefinitionType {
52 fn validate(
53 &self,
54 _: &State,
55 path: Vec<String>,
56 input: &serde_json::Value,
57 ) -> Result<(), ValidationError> {
58 use crate::definition::Type::*;
59
60 let err_msg = match self.typ {
61 Null => {
62 if input.is_null() {
63 return Ok(());
64 }
65 "Value must be null."
66 }
67 Boolean => {
68 if input.is_boolean() {
69 return Ok(());
70 }
71 "Value must be boolean."
72 }
73 String => {
74 if input.is_string() {
75 return Ok(());
76 }
77 "Value must be a string."
78 }
79 Number => {
80 if input.is_number() {
81 return Ok(());
82 }
83 "Value must be a number."
84 }
85 Integer => {
86 if input.is_i64() {
87 return Ok(());
88 }
89 "Value must be a integer."
90 }
91 Object => {
92 if input.is_object() {
93 return Ok(());
94 }
95 "Value must be an object."
96 }
97 Array => {
98 if input.is_array() {
99 return Ok(());
100 }
101 "Value must be an array."
102 }
103 _ => return Ok(()), };
105
106 Err(ValidationError::Failure {
107 rule: self.name.clone(),
108 path: path,
109 message: err_msg.to_string(),
110 })
111 }
112}