Skip to content

Instantly share code, notes, and snippets.

@ivanoronee
Created September 14, 2017 13:29
Show Gist options
  • Save ivanoronee/9cdc8ef5854266a866b8100702930280 to your computer and use it in GitHub Desktop.
Save ivanoronee/9cdc8ef5854266a866b8100702930280 to your computer and use it in GitHub Desktop.
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