Skip to main content

zio

yoshi-zio lets a validation target zio core types: a Chunk validates into a NonEmptyChunk, and a NonEmptyChunk validates element by element.

Setup​

libraryDependencies += "dev.hshn" %% "yoshi-zio" % "0.6.0"

Having the module on the classpath is enough — import yoshi.* brings its instances in along with the core syntax. Nothing else to import.

import yoshi.*
import yoshi.defaults.*

Chunks​

A NonEmptyChunk[A] validates element by element, and each violation is reported under the index of the element it came from:

import zio.Chunk
import zio.NonEmptyChunk
NonEmptyChunk("1", "x", "3").validateAs[NonEmptyChunk[Int]].left.map(_.toList)
// res0: Either[List[Tuple2[Paths, Err]], NonEmptyChunk[Int]] = Left(
// List((Paths(List(Index(1))), NonIntegerString("x")))
// )

A Chunk[A] can be validated into a NonEmptyChunk[B] too. The output type says the domain needs at least one element, so an empty input fails with the Required violation — the same one an absent Option reports:

Chunk("1", "2").validateAs[NonEmptyChunk[Int]]
// res1: Either[Violations[Err], NonEmptyChunk[Int]] = Right(
// NonEmptyChunk(1, 2)
// )
Chunk.empty[String].validateAs[NonEmptyChunk[Int]].left.map(_.toList)
// res2: Either[List[Tuple2[Paths, Err]], NonEmptyChunk[Int]] = Left(
// List((Paths(List()), Required))
// )

Inside a cursor this reads like any other field:

case class FormInput(tags: Chunk[String])
case class Post(tags: NonEmptyChunk[Int])

val post: Validation[Violation, FormInput, Post] =
Validation.cursor[FormInput] { c =>
(
c.validateAs[NonEmptyChunk[Int]](_.tags)
).validateN { tags =>
Post(tags)
}
}
post.run(FormInput(tags = Chunk("1", "x"))).left.map(_.toList)
// res3: Either[List[Tuple2[Paths, Violation]], Post] = Left(
// List((Paths(List(Key("tags"), Index(1))), NonIntegerString("x")))
// )
post.run(FormInput(tags = Chunk.empty)).left.map(_.toList)
// res4: Either[List[Tuple2[Paths, Violation]], Post] = Left(
// List((Paths(List(Key("tags"))), Required))
// )

As with the core derivations, the module knows nothing about your violation type. It reports an empty input through the Required instance — yoshi.defaults supplies one for Violation, and a violation type of your own needs a single given Required[MyViolation], as described in Getting Started.