Created
September 14, 2017 13:29
-
-
Save ivanoronee/9cdc8ef5854266a866b8100702930280 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
implicit class JsPathMixin(path: JsPath) extends JsPath { | |
def readOrError[T](fieldMissingError: => String)(implicit r: Reads[T]): Reads[T] = (json: JsValue) => { | |
path.readNullable(r) | |
.reads(json) match { | |
case JsSuccess(Some(value), _) => JsSuccess(value, path) | |
case JsSuccess(None, _) => JsError(path, JsonValidationError(fieldMissingError)) | |
case err@JsError(_) => | |
err | |
} | |
} | |
def readOrError[T](fieldMissingError: => String, | |
constraintValidationError: => String)(implicit r: Reads[T]): Reads[T] = (json: JsValue) => { | |
path.readNullable(r) | |
.reads(json) match { | |
case JsSuccess(Some(value), _) => JsSuccess(value, path) | |
case JsSuccess(None, _) => JsError(path, JsonValidationError(fieldMissingError)) | |
case err@JsError(_) => | |
JsError(path, JsonValidationError(constraintValidationError)) | |
} | |
} | |
} | |
def formatValidationErrors(errors: Seq[(JsPath, Seq[JsonValidationError])]): JsObject = { | |
errors.foldLeft(JsObject.empty) { (obj, error) => | |
obj ++ JsObject(Seq(error._1.toString.replaceFirst("/", "") -> error._2.foldLeft(JsArray.empty) { (arr, err) => | |
val msg = { | |
err.messages.map(JsString).toArray[JsValue] | |
} | |
msg.foldLeft(arr) { (acc, err) => acc :+ err } | |
})) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment