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
use crate::make_schema::MakeSchema;
use crate::schema::*;
use crate::{MakeSchemaError, Map, Result};

#[derive(Debug, PartialEq, Clone)]
pub struct SchemaSettings {
    pub option_nullable: bool,
    pub option_add_null_type: bool,
    pub bool_schemas: BoolSchemas,
    pub definitions_path: String,
}

#[derive(Debug, PartialEq, Copy, Clone)]
pub enum BoolSchemas {
    Enable,
    AdditionalPropertiesOnly,
    Disable,
}

impl Default for SchemaSettings {
    fn default() -> SchemaSettings {
        SchemaSettings {
            option_nullable: false,
            option_add_null_type: true,
            bool_schemas: BoolSchemas::Enable,
            definitions_path: "#/definitions/".to_owned(),
        }
    }
}

impl SchemaSettings {
    pub fn new() -> SchemaSettings {
        SchemaSettings {
            ..Default::default()
        }
    }
    pub fn openapi3() -> SchemaSettings {
        SchemaSettings {
            option_nullable: true,
            option_add_null_type: false,
            bool_schemas: BoolSchemas::AdditionalPropertiesOnly,
            definitions_path: "#/components/schemas/".to_owned(),
        }
    }

    pub fn into_generator(self) -> SchemaGenerator {
        SchemaGenerator::new(self)
    }
}

#[derive(Debug, Default, Clone)]
pub struct SchemaGenerator {
    settings: SchemaSettings,
    definitions: Map<String, Schema>,
}

impl SchemaGenerator {
    pub fn new(settings: SchemaSettings) -> SchemaGenerator {
        SchemaGenerator {
            settings,
            ..Default::default()
        }
    }

    pub fn settings(&self) -> &SchemaSettings {
        &self.settings
    }

    pub fn schema_for_any(&self) -> Schema {
        if self.settings().bool_schemas == BoolSchemas::Enable {
            true.into()
        } else {
            Schema::Object(Default::default())
        }
    }

    pub fn schema_for_none(&self) -> Schema {
        if self.settings().bool_schemas == BoolSchemas::Enable {
            false.into()
        } else {
            Schema::Object(SchemaObject {
                not: Some(Schema::Object(Default::default()).into()),
                ..Default::default()
            })
        }
    }

    pub fn subschema_for<T: ?Sized + MakeSchema>(&mut self) -> Result {
        if !T::is_referenceable() {
            return T::make_schema(self);
        }

        let name = T::schema_name();
        if !self.definitions.contains_key(&name) {
            self.insert_new_subschema_for::<T>(name.clone())?;
        }
        let reference = format!("{}{}", self.settings().definitions_path, name);
        Ok(Ref { reference }.into())
    }

    fn insert_new_subschema_for<T: ?Sized + MakeSchema>(&mut self, name: String) -> Result<()> {
        let dummy = Schema::Bool(false);
        // insert into definitions BEFORE calling make_schema to avoid infinite recursion
        self.definitions.insert(name.clone(), dummy);

        match T::make_schema(self) {
            Ok(schema) => {
                self.definitions.insert(name.clone(), schema);
                Ok(())
            }
            Err(e) => {
                self.definitions.remove(&name);
                Err(e)
            }
        }
    }

    pub fn definitions(&self) -> &Map<String, Schema> {
        &self.definitions
    }

    pub fn into_definitions(self) -> Map<String, Schema> {
        self.definitions
    }

    pub fn root_schema_for<T: ?Sized + MakeSchema>(&mut self) -> Result {
        let schema = T::make_schema(self)?;
        Ok(match schema {
            Schema::Object(mut o) => {
                o.schema = Some("http://json-schema.org/draft-07/schema#".to_owned());
                o.title = Some(T::schema_name());
                o.definitions.extend(self.definitions().clone());
                Schema::Object(o)
            }
            schema => schema,
        })
    }

    pub fn into_root_schema_for<T: ?Sized + MakeSchema>(mut self) -> Result {
        let schema = T::make_schema(&mut self)?;
        Ok(match schema {
            Schema::Object(mut o) => {
                o.schema = Some("http://json-schema.org/draft-07/schema#".to_owned());
                o.title = Some(T::schema_name());
                o.definitions.extend(self.into_definitions());
                Schema::Object(o)
            }
            schema => schema,
        })
    }

    pub(crate) fn get_schema_object<'a>(&'a self, mut schema: &'a Schema) -> Result<SchemaObject> {
        loop {
            match schema {
                Schema::Object(o) => return Ok(o.clone()),
                Schema::Bool(true) => return Ok(Default::default()),
                Schema::Bool(false) => {
                    return Ok(SchemaObject {
                        not: Some(Schema::Bool(true).into()),
                        ..Default::default()
                    })
                }
                Schema::Ref(r) => {
                    let definitions_path_len = self.settings().definitions_path.len();
                    let name = r.reference.get(definitions_path_len..).ok_or_else(|| {
                        MakeSchemaError::new(
                            "Could not extract referenced schema name.",
                            Schema::Ref(r.clone()),
                        )
                    })?;

                    schema = self.definitions.get(name).ok_or_else(|| {
                        MakeSchemaError::new(
                            "Could not find referenced schema.",
                            Schema::Ref(r.clone()),
                        )
                    })?;

                    match schema {
                        Schema::Ref(r2) if r2 == r => {
                            return Err(MakeSchemaError::new(
                                "Schema is referencing itself.",
                                schema.clone(),
                            ));
                        }
                        _ => {}
                    }
                }
            }
        }
    }
}