Skip to content

Instantly share code, notes, and snippets.

@imeredith
Created September 12, 2012 03:50
Show Gist options
  • Save imeredith/3704179 to your computer and use it in GitHub Desktop.
Save imeredith/3704179 to your computer and use it in GitHub Desktop.
case class SomeModel(field1: String, field2: String)
def index = Action(parse.json) { implicit request =>
val validation = for {
field1 <- js[String]("field1")
field2 <- js[String]("field2")
} yield (field1 |@| field2)(SomeModel.apply)
validation(request.body).fold(
e => BadRequest(Json.toJson(Map("errors" -> Json.toJson(e.toList)))),
s => Ok(Json.toJson(Map("field1" -> s.field1, "field2" -> s.field2)))
)
}
def js[A:Reads](field: String): JsValue => ValidationNEL[String, A] = j => (j \ field).asOpt[A] toSuccess ("Field '%s' not found" format field).point[NonEmptyList]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment