Pudu programming language
Menu
Package

@chrismichaelps / pudu-lang-validator

Typed fluent validation rules for Pudu

0.1.1Apache-2.01

InstallClose

Result.pudu

Pudu54 lines1.8 KB

GitHub ↗
1/** @Validation.Result.Model — preserves ordered validation failures */2module PuduLangValidator.Result34import Std.Map as Map5import Std.Text as Text67/** @Validation.Result.Severity — classifies a failed rule */8export type Severity = Error | Warning | Info910/** @Validation.Result.Failure — locates one failed check */11export type Failure = {12  propertyName: Str,13  errorMessage: Str,14  errorCode: Str,15  severity: Severity,16  customState: Str17}1819/** @Validation.Result.ValidationResult — retains failures in rule order */20export type ValidationResult = { isValid: Bool, errors: Array[Failure] }2122/// A result whose validity agrees with its failures.23export fn fromFailures(errors: Array[Failure]) -> ValidationResult {24  ValidationResult{isValid: errors.isEmpty(), errors: errors}25}2627/// The failure messages joined in encounter order.28export fn messages(result: &ValidationResult, separator: Str) -> Str {29  Text.join(&result.errors.map(|failure: Failure| failure.errorMessage), separator)30}3132/// Failures at exactly one property path.33export fn forProperty(result: &ValidationResult, name: Str) -> Array[Failure] {34  result.errors.filter(|failure: Failure| failure.propertyName == name)35}3637/// Group messages by exact failure path, preserving order within each path.38export fn toDictionary(result: &ValidationResult) -> Map[Str, Array[Str]] {39  var grouped: Map[Str, Array[Str]] = mapOf([])40  for failure in result.errors {41    let existing = match Map.get(&grouped, failure.propertyName) {42      case Some(held) => held43      case None => []44    }45    grouped = grouped.insert(failure.propertyName, existing.push(failure.errorMessage))46  }47  grouped48}4950/// Keep the source on success, or return every validation failure.51export fn toResult[T](result: &ValidationResult, value: T) -> Result[T, Array[Failure]] {52  if result.isValid { Ok(value) } else { Err(result.errors) }53}54