Skip to content

Instantly share code, notes, and snippets.

@megri
Last active March 15, 2018 08:36
Show Gist options
  • Save megri/7a4be59cc619614ed3063a190243a7b2 to your computer and use it in GitHub Desktop.
Save megri/7a4be59cc619614ed3063a190243a7b2 to your computer and use it in GitHub Desktop.
import cats.syntax.apply._
import io.circe._
import io.circe.literal._
object JsonValidation{
def validate[A: Decoder]( f: HCursor => ACursor, pred: A => Boolean, err: A => String ): Decoder[A] =
Decoder.instance(
f andThen{ ac =>
ac.as[A].flatMap( a =>
if ( pred( a ) )
Right( a )
else
Left( DecodingFailure( err( a ), ac.history ) ) )
}
)
}
implicit val someRequestDecoder: Decoder[SomeRequest] ={
def stringOfLength( min: Int, max: Int )( f: HCursor => ACursor ): Decoder[String] =
JsonValidation.validate[String]( f, s => s.length >= min && s.length <= max,
s => s"Length must be between $min and $max; was ${s.length}" )
val name = stringOfLength( 1, 10 )( _.downField( "name" ) )
val desc = stringOfLength( 0, 20 )( _.downField( "description" ) )
( name, desc ).mapN( SomeRequest )
}
case class SomeRequest( name: String, description: String )
val name = "A name too long"
val desc = "this description is longer than 20 characters"
val json = json"""{ "name": $name, "description": $desc }"""
Decoder[SomeRequest].accumulating.apply( json.hcursor )
@voidcontext
Copy link

You can do (almost) the same with validate method:

import io.circe.generic.semiauto.deriveDecoder
import io.circe._
import io.circe.parser.decode

case class SomeRequest( name: String, description: String )

def genValidator(field: String): HCursor => Boolean =
  (c: HCursor) => {
    c.downField(field)
      .focus
      .exists(
        _.as[String]
          .right
          .map(v => v.length >= 5 && v.length < 10)
          .getOrElse(true)
    )
  }

implicit class DecoderOps[A](decoder: Decoder[A]) {
  def validateStringLenght(field: String) = decoder.validate(genValidator(field), s"Length of '${field}' is not within limits")
}

implicit val decoder = deriveDecoder[SomeRequest]
  .validateStringLenght("name")
  .validateStringLenght("description")

val json = "{\"name\": \"foo\", \"description\": \"bar\"}"

decode[SomeRequest](json)

Edge cases (e.g. when the given field doesn't exist) might not be handled properly.

What do you think?

@megri
Copy link
Author

megri commented Mar 8, 2018

Hi, thanks for the example!

There are two problems with this approach—which is why I came up with the alternative shown in this gist:

  1. It doesn't seem to accumulate decoding failures. This could be due to the bug you mentioned earlier;
  2. It shadows more generic error messages such that the field has the wrong type or doesn't exist in the input. This means that you have to include those cases in your custom error message.

If the first argument of .validate were to be HCursor => Decoder.Result[A] it would be possible to keep the generic error messages. This is basically what the gist does but it opts for a HCursor => ACursor to make the call-site look a bit cleaner.

@voidcontext
Copy link

Ok, I think I understand what was the confusion (at least from my perspective): my code is attaching the validation of the individual fields to the containing JSON element. The accumulation is not working as apparently 1 element can only have 1 error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment