Last active
May 20, 2016 18:41
-
-
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
This file contains hidden or 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
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