Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Server.start(8080, app)
.provide(
clientLayers,
NumService.live,
WordService.live,
ZLayer.Debug.mermaid // Generates Mermaid.JS graphs
)
.exitCode
import zhttp.service.{ChannelFactory, Client, EventLoopGroup}
import zio.{Tag, ZEnvironment, ZIO, ZLayer}
trait NumService:
val get: ZIO[Any, Throwable, Int]
final case class NumServiceLive(c: ChannelFactory, e: EventLoopGroup) extends NumService:
val url = "https://random-num-x5ht4amjia-uc.a.run.app/"
val get: ZIO[Any, Throwable, Int] =
val request =
for
resp <- Client.request(url)
body <- resp.bodyAsString
yield body.toInt
request.provideEnvironment(ZEnvironment(c, e))
object NumService:
val get: ZIO[NumService, Throwable, Int] = ZIO.serviceWithZIO[NumService](_.get)
val live: ZLayer[ChannelFactory & EventLoopGroup, Nothing, NumService] =
ZLayer.fromZIO(
for {
c <- ZIO.service[ChannelFactory]
e <- ZIO.service[EventLoopGroup]
} yield NumServiceLive(c, e)
)
trait WordService:
val get: ZIO[Any, Throwable, String]
case class WordServiceLive(c: ChannelFactory, e: EventLoopGroup) extends WordService:
val url = "https://random-word-x5ht4amjia-uc.a.run.app/"
val get: ZIO[Any, Throwable, String] =
val z =
for
resp <- Client.request(url)
body <- resp.bodyAsString
yield body
z.provideEnvironment(ZEnvironment(c, e))
object WordService:
val get: ZIO[WordService, Throwable, String] = ZIO.serviceWithZIO[WordService](_.get)
val live: ZLayer[ChannelFactory & EventLoopGroup, Nothing, WordService] =
ZLayer.fromZIO(
for {
c <- ZIO.service[ChannelFactory]
e <- ZIO.service[EventLoopGroup]
} yield WordServiceLive(c, e)
)
import zhttp.http.{Http, Response}
import zhttp.service.{ChannelFactory, EventLoopGroup, Server}
import zio.{ZIO, ZIOAppDefault, ZLayer}
object WebApp extends ZIOAppDefault:
def gibberish: ZIO[NumService & WordService, Throwable, String] =
for
num <- NumService.get
reqs = Seq.fill(num)(WordService.get)
words <- ZIO.collectAllPar(reqs)
yield words.mkString(" ")
val app =
Http.fromZIO(gibberish.map(Response.text))
def run =
val clientLayers = ChannelFactory.auto ++ EventLoopGroup.auto()
Server.start(8080, app)
.provide(
clientLayers,
NumService.live,
WordService.live,
)
.exitCode
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment