Skip to content

Instantly share code, notes, and snippets.

@galaux
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save galaux/053e52dd4e0dc6c6aa0a to your computer and use it in GitHub Desktop.
Save galaux/053e52dd4e0dc6c6aa0a to your computer and use it in GitHub Desktop.
package controllers
import play.api._
import play.api.mvc._
import play.api.data.validation.ValidationError
import play.api.libs.json._
object Application extends Controller {
import play.api.libs.json._
import play.api.libs.json.Reads._
import play.api.libs.functional.syntax._
case class Location(bla: Bla.Value, lat: Double, long: Double, lastName: String)
case class ThisThing(up: String, down: Int)
implicit val locationReads: Reads[Location] = (
(__ \ "bla").read[Bla.Value] and
(__ \ "lat").read[Double] and
(__ \ "long").read[Double] and
(__ \ "lastName").read[String]
)(Location.apply _)
implicit val thisThingReads: Reads[ThisThing] = (
(__ \ "up").read[String] and
(__ \ "down").read[Int]
)(ThisThing.apply _)
case class MyResult(fieldOne: String, fieldTwo: Double)
implicit def myResultWrites = Writes[MyResult] { res =>
Json.obj(
"fieldOne" -> res.fieldOne,
"fieldTwo" -> res.fieldTwo)
}
def doAction[A1:Reads, A2:Reads, B:Writes](p: Tuple2[String,String])(bizMethod: (A1, A2) => B) =
Action(BodyParsers.parse.json) { request =>
val res = List(
(request.body \ p._1).validate[A1],
(request.body \ p._2).validate[A2]
)
res.partition(_.isError) match {
case (List(), ok) =>
val res: B = bizMethod(ok.head.get.asInstanceOf[A1], ok.last.get.asInstanceOf[A2])
Ok(Json.toJson(res))
case (errs, _) => BadRequest(errs.toString)
}
}
def myPost(id: Long) = doAction(("location", "thisThing"))({
(loc: Location, thisThing: ThisThing) =>
MyResult(thisThing.up + "_" + loc.bla, loc.lat + thisThing.down)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment