Skip to content

Instantly share code, notes, and snippets.

@mkotsbak
Last active May 20, 2016 18:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mkotsbak/08b808d5152c96b65b4d to your computer and use it in GitHub Desktop.
Save mkotsbak/08b808d5152c96b65b4d to your computer and use it in GitHub Desktop.
Play server wiring to get Autowire to work with extra request information like IP-addresses and authentication. See how to use it here: https://gist.github.com/mkotsbak/122940aa003db9708093
package controllers
import play.api.http.{ContentTypes, ContentTypeOf}
import upickle.Js
import upickle.default._
import play.api.mvc._
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
object PlayAutowire extends Controller {
implicit def contentTypeOf_upickle_Js_Value(implicit jsValue: Js.Value) =
ContentTypeOf[Js.Value](Some(ContentTypes.JSON))
case class AutowireContext(playRequest: RequestHeader)
trait AutowirePlayServer[T] extends autowire.Server[Js.Value, Reader, Writer] {
def write[Result: Writer](r: Result) = writeJs(r)
def read[Result: Reader](p: Js.Value) = readJs[Result](p)
def routes(target: T): Router
def createImpl(autowireContext: AutowireContext): T
}
def api[T](server: AutowirePlayServer[T])(s: String) = Action.async { implicit request =>
val path = s.split("/").toSeq
request.body.asJson.map { json =>
val args = json.toString()
upickle.json.read(args) match {
case Js.Obj(objArgs @ _*) =>
val req = autowire.Core.Request(path, objArgs.toMap)
val requestSession = server.createImpl(
AutowireContext(playRequest = request)
)
server.routes(requestSession)(req).flatMap { responseData =>
Future.successful(Ok(upickle.json.write(responseData)))
}
case _ =>
Future.failed(new Exception("Arguments need to be a valid JSON object"))
}
}.getOrElse {
println("Got bad request: " + request.body.asRaw.toString)
Future.successful(BadRequest)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment