use crate::{Error, Result};
use jsonschema::{self, Draft};
use openapiv3::Schema;
use serde_json::Value;
#[derive(Debug, Clone)]
pub struct OpenApiSchema {
pub schema: Schema,
}
impl OpenApiSchema {
pub fn new(schema: Schema) -> Self {
Self { schema }
}
pub fn validate(&self, value: &Value) -> Result<()> {
match serde_json::to_value(&self.schema) {
Ok(schema_json) => {
match jsonschema::options().with_draft(Draft::Draft7).build(&schema_json) {
Ok(validator) => {
let errors: Vec<String> =
validator.iter_errors(value).map(|error| error.to_string()).collect();
if errors.is_empty() {
Ok(())
} else {
Err(Error::validation(errors.join("; ")))
}
}
Err(e) => {
Err(Error::validation(format!("Failed to create schema validator: {}", e)))
}
}
}
Err(e) => {
Err(Error::validation(format!("Failed to convert OpenAPI schema to JSON: {}", e)))
}
}
}
}
#[derive(Debug, Clone)]
pub struct ValidationResult {
pub valid: bool,
pub errors: Vec<String>,
}
impl ValidationResult {
pub fn valid() -> Self {
Self {
valid: true,
errors: Vec::new(),
}
}
pub fn invalid(errors: Vec<String>) -> Self {
Self {
valid: false,
errors,
}
}
}