Created
May 4, 2017 15:36
-
-
Save longliveenduro/cde5f09f41ed6641846687caf89bfc52 to your computer and use it in GitHub Desktop.
Converting Play Json's JsLookupResult to Scalactic's Good Or Bad
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 org.scalactic._ | |
import play.api.libs.json.{JsError, JsLookupResult, JsSuccess, Reads} | |
object RichJsLookupResult { | |
implicit class RichPlayJsonValidateToGoodOrBad(lookupResult: JsLookupResult) { | |
def parseAs[T](implicit rds: Reads[T]): T Or Every[String] = { | |
lookupResult.validate[T] match { | |
case s: JsSuccess[T] => Good(s.get) | |
case e: JsError => | |
val errorMessages = e.errors.map { | |
case (path, errors) if path.toString().trim != "" => path.toString() + ": " + errors.map(_.message).mkString(", ") | |
case (_, errors) => errors.map(_.message).mkString(", ") | |
} | |
errorMessages.toList match { | |
case Nil => throw new Exception(s"Error messages are expected but empty for $lookupResult") | |
case msg :: Nil => Bad(One(msg)) | |
case h :: rest => Bad(Every(h, rest: _*)) | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment