Created
April 7, 2021 10:57
-
-
Save paulpdaniels/734b73dcce4d18f94b0129ca7db8a2a5 to your computer and use it in GitHub Desktop.
Play ZIO interop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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