Last active
March 15, 2018 08:36
-
-
Save megri/7a4be59cc619614ed3063a190243a7b2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ) |
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:
- It doesn't seem to accumulate decoding failures. This could be due to the bug you mentioned earlier;
- 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.
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
You can do (almost) the same with validate method:
Edge cases (e.g. when the given field doesn't exist) might not be handled properly.
What do you think?