Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Decoder#validate allowing building the message from the trigger HCursor #1020

Merged
merged 3 commits into from Dec 14, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
30 changes: 25 additions & 5 deletions modules/core/shared/src/main/scala/io/circe/Decoder.scala
Expand Up @@ -154,21 +154,41 @@ trait Decoder[A] extends Serializable { self =>
}

/**
* Build a new instance that fails if the condition does not hold for the
* input.
* Build a new instance that fails with one or more errors if the condition
* does not hold for the input.
*
* Note that this condition is checked before decoding with the current
* decoder, and if it does not hold, decoding does not continue. This means
* that if you chain calls to this method, errors will not be accumulated
* (instead only the error of the last failing `validate` in the chain will be
* returned).
*/
final def validate(pred: HCursor => Boolean, message: => String): Decoder[A] = new Decoder[A] {
final def validate(errors: HCursor => List[String]): Decoder[A] = new Decoder[A] {
final def apply(c: HCursor): Decoder.Result[A] =
if (pred(c)) self(c) else Left(DecodingFailure(message, c.history))
errors(c).headOption.map { message =>
Left(DecodingFailure(message, c.history))
} getOrElse self(c)

override def decodeAccumulating(c: HCursor): AccumulatingDecoder.Result[A] =
if (pred(c)) self.decodeAccumulating(c) else Validated.invalidNel(DecodingFailure(message, c.history))
errors(c).map(DecodingFailure(_, c.history)) match {
case Nil => self.decodeAccumulating(c)
case h :: t => Validated.invalid(NonEmptyList(h, t))
}
}

/**
* Build a new instance that fails if the condition does not hold for the
* input.
*
* Note that this condition is checked before decoding with the current
* decoder, and if it does not hold, decoding does not continue. This means
* that if you chain calls to this method, errors will not be accumulated
* (instead only the error of the last failing `validate` in the chain will be
* returned).
*/
final def validate(pred: HCursor => Boolean, message: => String): Decoder[A] = validate { c =>
if (pred(c)) Nil
else message :: Nil
}

/**
Expand Down
25 changes: 25 additions & 0 deletions modules/tests/shared/src/test/scala/io/circe/DecoderSuite.scala
Expand Up @@ -404,6 +404,31 @@ class DecoderSuite extends CirceSuite with LargeNumberDecoderTests with TableDri
assert(validatingDecoder.decodeAccumulating(Json.True.hcursor).isInvalid)
}

it should "provide the generated error messages from HCursor when a function is passed" in {
case class Foo(x: Int, y: String)

val decoder: Decoder[Foo] = Decoder.const(Foo(42, "meaning")).validate { c =>
val maybeFieldsStr = for {
json <- c.focus
jsonKeys <- json.hcursor.keys
} yield jsonKeys.mkString(",")
maybeFieldsStr.getOrElse("") :: Nil
}

val Right(fooJson) = parse("""{"x":42, "y": "meaning"}""")

assert(decoder.decodeJson(fooJson).left.get.message === "x,y")
}

it should "not fail when the passed errors function returns an empty list" in {
val testValue = 42
val decoder = Decoder[Int].validate(_ => Nil)

val Right(intJson) = parse(testValue.toString)

assert(decoder.decodeJson(intJson) === Right(testValue))
}

"either" should "return the correct disjunct" in forAll { (value: Either[String, Boolean]) =>
val json = value match {
case Left(s) => Json.fromString(s)
Expand Down