pactum-annotations 0.1.0

Declarative field normalization and validation for pactum contracts
Documentation
use serde::{Deserialize, Serialize};

/// One field (or whole-model) invariant that failed.
///
/// The text field is `reason` so UniFFI Kotlin exceptions never collide with
/// `Throwable.message`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FieldIssue {
    /// JSON / MessagePack key, or `"body"` for a whole-object failure.
    pub field: String,
    /// Stable machine code (`INVALID_EMAIL`, `STRING_TOO_LONG`, …).
    pub code: String,
    /// Human-readable explanation.
    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 {}

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(())
    }
}