Created
April 10, 2018 16:25
-
-
Save x7c1/348ede080861a7fe16083c5351fc60d1 to your computer and use it in GitHub Desktop.
Controller to handle a custom request on Play Framework
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.mvc.{ActionBuilder, AnyContent, BaseController, BodyParser, Request, Result} | |
| import scala.concurrent.{ExecutionContext, Future} | |
| case class CustomRequest[A](underlying: Request[A]) { | |
| def body: A = underlying.body | |
| } | |
| class CustomActionBuilder[B](val parser: BodyParser[B])( | |
| implicit protected val executionContext: ExecutionContext, | |
| ) extends ActionBuilder[CustomRequest, B] { | |
| override def invokeBlock[A]( | |
| request: Request[A], | |
| block: CustomRequest[A] => Future[Result]): Future[Result] = { | |
| // any pre-process here | |
| block(CustomRequest(request)) | |
| } | |
| } | |
| trait CustomController { | |
| self: BaseController => | |
| private lazy val customActionBuilder = { | |
| val parser = controllerComponents.parsers.defaultBodyParser | |
| val context = controllerComponents.executionContext | |
| new CustomActionBuilder[AnyContent](parser)(context) | |
| } | |
| def CustomAction: ActionBuilder[CustomRequest, AnyContent] = customActionBuilder | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment