Pudu programming language
Menu
Package

@chrismichaelps / pudu-lang-mediator

In-process messaging for Pudu: requests, notifications, streams, pipeline behaviors, processors, and exception handling

0.1.0Apache-2.01

InstallClose

Validation.pudu

Pudu45 lines2.2 KB

GitHub ↗
1/** @Mediator.Behaviors.Validation.Module — requests and streams refused when their rules fail */2module PuduLangMediator.Behaviors.Validation34import PuduLangMediator.Context as Context5import PuduLangMediator as Messaging6import PuduLangMediator.Registration as Registration7import PuduLangMediator.Request as Request8import PuduLangMediator.Stream as Stream9import PuduLangValidator.Result as Validated10import PuduLangValidator.Validator as Validator1112/// A behavior answering `Invalid` with every violation when `validator` rejects the request, and13/// running the rest of the pipeline otherwise.14export fn behavior[Q, R, E](validator: Validator.Validator[Q]) -> Request.Behavior[Q, R, E] {15  fn(request: Q, context: Context.Context, next: Request.Next[R, E]) -> Messaging.Outcome[R, E] {16    let result = Validator.validate(&validator, request)17    if result.isValid { next(context) } else { Err(Messaging.Invalid(violationsOf(&result))) }18  }19}2021/// The validation behavior of one request kind.22export fn register[Q, R, E](subject: &Request.Kind[Q, R, E], validator: Validator.Validator[Q]) -> Registration.Registration {23  Registration.behavior(subject, behavior(validator))24}2526/// A stream behavior answering `Invalid` before any item when `validator` rejects the request.27export fn streamBehavior[Q, T, E](validator: Validator.Validator[Q]) -> Stream.Behavior[Q, T, E] {28  fn(request: Q, context: Context.Context, sink: Stream.Sink[T], next: Stream.Next[T, E]) -> Messaging.Outcome[(), E] {29    let result = Validator.validate(&validator, request)30    if result.isValid { next(context, sink) } else { Err(Messaging.Invalid(violationsOf(&result))) }31  }32}3334/// The stream validation behavior of one stream kind.35export fn registerStream[Q, T, E](subject: &Stream.Kind[Q, T, E], validator: Validator.Validator[Q]) -> Registration.Registration {36  Registration.streamBehavior(subject, streamBehavior(validator))37}3839/// Every failure of a validation result as a violation, in rule order.40export fn violationsOf(result: &Validated.ValidationResult) -> Array[Messaging.Violation] {41  result.errors.map(fn(failure: Validated.Failure) -> Messaging.Violation {42      Messaging.Violation{property: failure.propertyName, message: failure.errorMessage, code: failure.errorCode}43    })44}45