1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
//! This crates provides simply the `Schema` struct. It resembles the latest (draft-07) [json-schema core spec](https://json-schema.org/latest/json-schema-core.html).
//! If this spec is no longer up-to-date by the time you read this, please open a [new issue](https://github.com/hoodie/serde-json-schema/issues/new).
//!
//! If this type seems a bit confusing, then it's because json-schema is a bit too flexible.
//!
//! ## Usage
//!
//! ```
//! use serde_json_schema::Schema;
//! # use std::convert::TryFrom;
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # use std::fs;
//! let schema_file = fs::read_to_string("./examples/address.schema.json")?;
//! let address_schema = Schema::try_from(schema_file)?;
//! # Ok(())
//! # }
//! ```

use serde::{Deserialize, Serialize};
pub use url::Url;

use std::collections::HashMap;
use std::convert::TryFrom;

pub mod id;
pub mod error;
pub mod property;
mod validation;

use crate::id::*;
use crate::property::*;

/// Represents a full JSON Schema Document
// TODO: root array vs object
#[derive(Debug, Serialize, Deserialize)]
pub struct Schema(SchemaInner);

/// Represents a full JSON Schema Document
// TODO: root array vs object
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
enum SchemaInner {
    /// The Common case
    Schema(SchemaDefinition),
    /// For Some stupid reason specs can just be `true` or `false`
    Boolean(bool),
}

impl Schema {
    pub fn draft_version(&self) -> Option<&str> {
        match &self.0 {
            SchemaInner::Schema(SchemaDefinition {
                schema: Some(schema),
                ..
            }) => schema
                .path_segments()
                .and_then(|mut segments| segments.next()),
            _ => None,
        }
    }

    fn as_definition(&self) -> Option<&SchemaDefinition> {
        match &self.0 {
            SchemaInner::Schema(definition @ SchemaDefinition { .. }) => Some(&definition),
            _ => None,
        }
    }

    pub fn id(&self) -> Option<&SchemaId> {
        self.as_definition().and_then(|d| d.id.as_ref())
    }

    pub fn schema(&self) -> Option<&Url> {
        self.as_definition().and_then(|d| d.schema.as_ref())
    }

    pub fn description(&self) -> Option<&str> {
        self.as_definition()
            .and_then(|d| d.description.as_ref().map(|s| s.as_str()))
    }

    pub fn specification(&self) -> Option<&PropertyInstance> {
        match &self.0 {
            SchemaInner::Schema(SchemaDefinition {
                specification: Some(Property::Value(specification @ PropertyInstance::Object { .. })),
                ..
            }) => Some(&specification),
            _ => None,
        }
    }

    pub fn properties(&self) -> Option<&HashMap<String, Property>> {
        match self.specification() {
            Some(PropertyInstance::Object { properties, .. }) => Some(properties),
            _ => None,
        }
    }

    pub fn required_properties(&self) -> Option<&Vec<String>> {
        match self.specification() {
            Some(PropertyInstance::Object { required, .. }) => required.as_ref(),
            _ => None,
        }
    }

    pub fn as_null(&self) -> Option<&PropertyInstance> {
        match self.specification() {
            Some(null @ PropertyInstance::Null) => Some(null),
            _ => None,
        }
    }

    pub fn as_boolean(&self) -> Option<&PropertyInstance> {
        match self.specification() {
            Some(boolean @ PropertyInstance::Boolean(_)) => Some(boolean),
            _ => None,
        }
    }

    pub fn as_integer(&self) -> Option<&PropertyInstance> {
        match self.specification() {
            Some(integer @ PropertyInstance::Integer { .. }) => Some(integer),
            _ => None,
        }
    }

    pub fn as_object(&self) -> Option<&PropertyInstance> {
        match self.specification() {
            Some(object @ PropertyInstance::Object { .. }) => Some(object),
            _ => None,
        }
    }

    pub fn as_array(&self) -> Option<&PropertyInstance> {
        match self.specification() {
            Some(array @ PropertyInstance::Array { .. }) => Some(array),
            _ => None,
        }
    }

    pub fn as_number(&self) -> Option<&PropertyInstance> {
        match self.specification() {
            Some(number @ PropertyInstance::Number { .. }) => Some(number),
            _ => None,
        }
    }

    pub fn validate(&self, json: &serde_json::Value) -> Result<(), Vec<String>> {
        match self.0 {
            SchemaInner::Schema(SchemaDefinition {
                specification: Some(Property::Value(ref prop)),
                ..
            }) => prop.validate(json),
            SchemaInner::Schema(SchemaDefinition {
                specification: Some(Property::Ref(_)),
                ..
            }) => unimplemented!(),
            SchemaInner::Boolean(true) => {
                eprintln!(r#"your schema is just "true", everything goes"#);
                Ok(())
            }
            SchemaInner::Boolean(false) => Err(vec![String::from(
                r##""the scheme "false" will never validate"##,
            )]),
            _ => Ok(()),
        }
    }
}

impl<'a> TryFrom<&str> for Schema {
    type Error = serde_json::error::Error;
    fn try_from(s: &str) -> Result<Schema, Self::Error> {
        serde_json::from_str(s)
    }
}

impl<'a> TryFrom<String> for Schema {
    type Error = serde_json::error::Error;
    fn try_from(s: String) -> Result<Schema, Self::Error> {
        serde_json::from_str(&s)
    }
}

impl<'a> TryFrom<&str> for SchemaDefinition {
    type Error = serde_json::error::Error;
    fn try_from(s: &str) -> Result<SchemaDefinition, Self::Error> {
        serde_json::from_str(s)
    }
}

impl<'a> TryFrom<String> for SchemaDefinition {
    type Error = serde_json::error::Error;
    fn try_from(s: String) -> Result<SchemaDefinition, Self::Error> {
        serde_json::from_str(&s)
    }
}

/// Represents a full JSON Schema Document, except when it is a boolean
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct SchemaDefinition {
    #[serde(rename = "$id")]
    pub id: Option<SchemaId>,

    #[serde(rename = "$schema")]
    pub schema: Option<Url>,
    pub description: Option<String>,
    // pub properties: HashMap<String, Property>,
    pub dependencies: Option<HashMap<String, Vec<String>>>,

    #[serde(flatten)]
    pub specification: Option<Property>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub definitions: Option<HashMap<String, SchemaDefinition>>,
}