avatar

Andres Jaimes

Using Cats Effect IO with the Play Framework

By Andres Jaimes

- 1 minutes read - 122 words

Cats Effect IO operations have to be performed at the highest level possible. So when working with the Play Framework the solution is to execute unsafeToFuture() in the controller methods.

def get = Action.async { implicit request =>
  service.get().map { items =>
    Ok(Json.toJson(items))
  }.unsafeToFuture()
}

We can as well write an Action implementation that automatically calls unsafeToFuture:

object IOHttp {

  implicit class ActionBuilderOps[+R[_], B](ab: ActionBuilder[R, B]) {

    import cats.effect.implicits._

    def asyncF[F[_] : Effect](cb: R[B] => F[Result]): Action[B] = ab.async { c =>
      cb(c).toIO.unsafeToFuture()
    }
  }
}

And then use it like this:

def get = Action.asyncF { implicit request =>
  service.get().map { items =>
    Ok(Json.toJson(items))
  }
}

References