ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Action composition
    scala/playframework 2023. 2. 19. 01:02

    https://github.com/playframework/play-samples/blob/2.8.x/play-scala-rest-api-example/app/v1/post/PostActionBuilder.scala 처럼 ActionBuilder 를 만드는 것도 좋은 것 같다.

     

    package controllers
    
    import play.api.Logging
    import play.api.mvc._
    
    import javax.inject._
    import scala.concurrent.{ExecutionContext, Future}
    
    class CustomAction @Inject() (parser: BodyParsers.Default)(implicit ec: ExecutionContext)
        extends ActionBuilderImpl(parser)
        with Logging {
      override def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]): Future[Result] = {
        println("Start Custom Action")
        block(request)
      }
    }
    
    case class AuthRequest[A](username: String, request: Request[A]) extends WrappedRequest[A](request)
    
    object MyActionRefiner {
      def auth(implicit ec: ExecutionContext): ActionRefiner[Request, AuthRequest] =
        new ActionRefiner[Request, AuthRequest] {
          override protected def refine[A](request: Request[A]): Future[Either[Result, AuthRequest[A]]] =
            Future.successful(Right(AuthRequest("windbird", request)))
    
    //    override protected def refine[A](request: Request[A]): Future[Either[Result, AuthRequest[A]]] =
    //      Future.successful(Left(Unauthorized("Not Permitted")))
    
          override protected def executionContext: ExecutionContext = ec
        }
    }
    
    @Singleton
    class ApiController @Inject() (cc: ControllerComponents, customAction: CustomAction)(
      implicit ec: ExecutionContext
    ) extends AbstractController(cc) {
      def api: Action[AnyContent] =
        Action.andThen(MyActionRefiner.auth)((request: AuthRequest[AnyContent]) => Ok(s"allowed user ${request.username}"))
    //    customAction.andThen(MyActionRefiner.auth)((request: AuthRequest[AnyContent]) => Ok(s"allowed user ${request.username}"))
    }

     

    설명

    ActionBuiler 끼리도 andThen 으로 composition 할 수 있다.

    customAction.andThen(customAction2)...

     

    참고: http://www.tzavellas.com/techblog/2015/02/10/action-composition-in-play-framework/

    'scala > playframework' 카테고리의 다른 글

    ScalaTest  (0) 2023.02.19
    Using ScalikeJDBC  (0) 2023.02.19
    Logging MDC  (0) 2023.02.19
    Deploy  (0) 2023.02.19
    Filter  (0) 2023.02.19

    댓글

Designed by Tistory.