Skip to content

Instantly share code, notes, and snippets.

@paulpdaniels
Created April 7, 2021 10:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulpdaniels/734b73dcce4d18f94b0129ca7db8a2a5 to your computer and use it in GitHub Desktop.
Save paulpdaniels/734b73dcce4d18f94b0129ca7db8a2a5 to your computer and use it in GitHub Desktop.
Play ZIO interop
import zio._
class Components(context: ApplicationLoader.Context)
extends BuiltInComponentsFromContext(context) {
// Initialize the layer
val appLayer = ZEnv.live ++ Users.live ++ Products.live
// Create a new runtime backed by the application layer
implicit val runtime = Runtime.unsafeFromLayer(appLayer)
// Pass around the runtime
val controller = new Controller(controllerComponents)(runtime)
// Handle shutdown of the application by shutting down the runtime as well
applicationLifecycle.addStopHook(() => Future(runtime.shutdown()))
lazy val routes = Router.from {
case GET(p"/me") => controller.me
}
}
class Controller(cc: ControllerComponents)(implicit runtime: Runtime[Users with Products]) extends AbstractController(cc) {
import ZioActions._
val me: EssentialAction = Action.asyncZio(_ => ZIO.succeed(Ok))
}
import zio._
object ZioActions {
implicit class ActionBuilderOps[+R[_], B](ab: ActionBuilder[R, B]) {
case class AsyncTaskBuilder[Ctx <: zio.Has[_]](dummy: Boolean = false) {
def apply(cb: R[B] => RIO[Ctx, Result])(implicit r: Runtime[Ctx]): Action[B] =
ab.async(c =>r.unsafeRunToFuture(cb(c)))
def apply[A](
bp: BodyParser[A]
)(cb: R[A] => RIO[Ctx, Result])(implicit r: Runtime[Ctx]): Action[A] =
ab.async[A](bp)(c => r.unsafeRunToFuture(cb(c)))
}
case class AsyncZioBuilder[Ctx <: zio.Has[_]](dummy: Boolean = false) {
def apply(cb: R[B] => ZIO[Ctx, Result, Result])(implicit r: Runtime[Ctx]): Action[B] =
ab.async(c => r.unsafeRunToFuture(cb(c).merge))
def apply[A](
bp: BodyParser[A]
)(cb: R[A] => ZIO[Ctx, Result, Result])(implicit r: Runtime[Ctx]): Action[A] =
ab.async[A](bp)(c => r.unsafeRunToFuture(cb(c).merge))
}
def asyncTask[Ctx <: zio.Has[_]] = AsyncTaskBuilder[Ctx]()
def asyncZio[Ctx <: zio.Has[_]] = AsyncZioBuilder[Ctx]()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment