Futures inside Directive monad.

37 views
Skip to first unread message

Aitor ATuin

unread,
May 30, 2014, 7:42:46 AM5/30/14
to unfilter...@googlegroups.com
Hello, i finally get some code like this:

Directive.Intent[Any, Any] {
   case Path(PostSeg(title :: Nil)) => for {
        _ <- GET
        _ <- Accepts.Json
        request <- Directives.request[Any]
        postEntry <- Directive((_:HttpRequest[Any]) => postEntry[A](title).run(config))
   } yield postEntry.onComplete {
          case Success(post) => post.fold[JsonResponse](BlogPostNotFound)(post => BlogSuccess(post.asJson))
          case Failure(t) => BlogPostNotFound
     }

where:

type ResultM[+A] = Result[ResponseFunction[Any],A]
postEntry[A] returns a Kleisli[ResultM, Config, Future[Option[A]]]

so at the end the postEntry is a Future[Option[PostEntry]].

Obviosly is not working because the onComplete is returning Unit and doesnt fit under the ResponseFunction type expected.

The more obvious way to solve this is to block the execution until the complete is done, but is there any better aproach?

Thanks.

Aitor ATuin

unread,
Jun 1, 2014, 10:21:24 AM6/1/14
to unfilter...@googlegroups.com
Finally i added a trait to be able to postpone the Future evaluation when the request is processed, so i can write it in this way:

val directiveIntent = AsyncDirective[Any, String] {
    case Path(Seg("test" :: "tres" :: Nil)) => for {
      _ <- GET
      delay <- data.as.Int.fail { (k, v) =>
        BadRequest ~> ResponseString(
          s"'$v' is not a valid int for $k"
        )
      } named "delay"
      request <- Directives.request[Any]
      v <- Directive((_: HttpRequest[Any]) => Result.Success(myfuture(delay.getOrElse(5000))))
    } yield AsyncResponse(v) {
        case scala.util.Success(v) => Ok ~> ResponseString("directiveIntent Succeded: " + v)
        case scala.util.Failure(t) => BadRequest ~> ResponseString("Error processing request")
      }
  }

Reply all
Reply to author
Forward
0 new messages