use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FieldIssue {
pub field: String,
pub code: String,
pub reason: String,
}
impl FieldIssue {
pub fn new(
field: impl Into<String>,
code: impl Into<String>,
reason: impl Into<String>,
) -> Self {
Self {
field: field.into(),
code: code.into(),
reason: reason.into(),
}
}
}
impl std::fmt::Display for FieldIssue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {} ({})", self.field, self.reason, self.code)
}
}
impl std::error::Error for FieldIssue {}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HostError {
pub code: String,
pub reason: String,
}
impl HostError {
pub fn new(code: impl Into<String>, reason: impl Into<String>) -> Self {
Self {
code: code.into(),
reason: reason.into(),
}
}
}
impl std::fmt::Display for HostError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}", self.code, self.reason)
}
}
impl std::error::Error for HostError {}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum AsyncValidationError {
Issues(Vec<FieldIssue>),
Host(HostError),
}
impl From<Vec<FieldIssue>> for AsyncValidationError {
fn from(issues: Vec<FieldIssue>) -> Self {
Self::Issues(issues)
}
}
impl From<HostError> for AsyncValidationError {
fn from(err: HostError) -> Self {
Self::Host(err)
}
}
impl std::fmt::Display for AsyncValidationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Issues(issues) => {
if let Some(first) = issues.first() {
write!(f, "{first}")
} else {
write!(f, "validation failed")
}
}
Self::Host(err) => write!(f, "{err}"),
}
}
}
impl std::error::Error for AsyncValidationError {}
impl crate::traits::Normalize for FieldIssue {
fn normalize(&mut self) {}
}
impl crate::traits::Validate for FieldIssue {
fn validate_with(&self, _ctx: &crate::context::ValidationContext) -> Result<(), Vec<FieldIssue>> {
Ok(())
}
}
impl<S> crate::traits::ScopedValidate<S> for FieldIssue {
fn validate_scoped_with(
&self,
_ctx: &crate::context::ValidationContext,
) -> Result<(), Vec<FieldIssue>> {
Ok(())
}
}
#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
impl<R: ?Sized + Sync, S> crate::traits::AsyncValidate<R, S> for FieldIssue {
async fn validate_async_with(
&self,
_ctx: &crate::context::ValidationContext,
_resolver: &R,
) -> Result<(), AsyncValidationError> {
Ok(())
}
}