Skip to content

Instantly share code, notes, and snippets.

@x7c1
Created April 10, 2018 16:25
Show Gist options
  • Select an option

  • Save x7c1/348ede080861a7fe16083c5351fc60d1 to your computer and use it in GitHub Desktop.

Select an option

Save x7c1/348ede080861a7fe16083c5351fc60d1 to your computer and use it in GitHub Desktop.
Controller to handle a custom request on Play Framework
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