ketzal_validation 0.1.1

Declarative models and validation for the Ketzal framework
Documentation
use serde::Serialize;

use super::components::Components;
use super::info::Info;
use super::schema::{Schema, ToSchema};

#[derive(Debug, Clone, Serialize)]
pub struct OpenApi {
    pub openapi: String,
    pub info: Info,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub components: Option<Components>,
}

impl OpenApi {
    pub fn new(title: impl Into<String>, version: impl Into<String>) -> Self {
        Self {
            openapi: "3.0.3".to_string(),
            info: Info::new(title, version),
            components: None,
        }
    }

    pub fn description(&mut self, description: impl Into<String>) -> &mut Self {
        self.info.description = Some(description.into());
        self
    }

    pub fn register<T: ToSchema>(&mut self, name: impl Into<String>) -> &mut Self {
        self.components().register::<T>(name);
        self
    }

    pub fn register_schema(&mut self, name: impl Into<String>, schema: Schema) -> &mut Self {
        self.components().register_schema(name, schema);
        self
    }

    pub fn components(&mut self) -> &mut Components {
        self.components.get_or_insert_with(Components::new)
    }

    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }

    pub fn to_yaml(&self) -> Result<String, serde_yaml::Error> {
        serde_yaml::to_string(self)
    }
}