use serde_json::Value;
use super::ZString;
use crate::error::{IssueCode, StringValidation, VldError};
use crate::schema::VldSchema;
pub struct ZParsedString<T> {
inner: ZString,
parse: fn(&str) -> Option<T>,
validation: StringValidation,
}
pub type ZUuid = ZParsedString<uuid::Uuid>;
pub type ZUrl = ZParsedString<url::Url>;
impl<T> Clone for ZParsedString<T> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
parse: self.parse,
validation: self.validation.clone(),
}
}
}
impl<T> ZParsedString<T> {
pub fn checks(mut self, f: impl FnOnce(ZString) -> ZString) -> Self {
self.inner = f(self.inner);
self
}
}
impl ZUuid {
pub fn new() -> Self {
Self {
inner: ZString::new().uuid(),
parse: |s| uuid::Uuid::parse_str(s).ok(),
validation: StringValidation::Uuid,
}
}
}
impl Default for ZUuid {
fn default() -> Self {
Self::new()
}
}
impl ZUrl {
pub fn new() -> Self {
Self {
inner: ZString::new().uri(),
parse: |s| url::Url::parse(s).ok(),
validation: StringValidation::Uri,
}
}
}
impl Default for ZUrl {
fn default() -> Self {
Self::new()
}
}
impl<T> VldSchema for ZParsedString<T> {
type Output = T;
fn parse_value(&self, value: &Value) -> Result<T, VldError> {
let s = self.inner.parse_value(value)?;
(self.parse)(&s).ok_or_else(|| {
VldError::from_code_with_value(
IssueCode::InvalidString {
validation: self.validation.clone(),
},
&Value::String(s),
)
})
}
}
#[cfg(feature = "openapi")]
impl<T> crate::openapi::JsonSchema for ZParsedString<T> {
fn json_schema(&self) -> Value {
self.inner.json_schema()
}
}
#[cfg(feature = "openapi")]
impl<T> crate::openapi::CollectNestedSchemas for ZParsedString<T> {}