Skip to content

Instantly share code, notes, and snippets.

@frekw
Created March 4, 2021 10:06
Show Gist options
  • Save frekw/8d671592ca202256835db8a82692ee24 to your computer and use it in GitHub Desktop.
Save frekw/8d671592ca202256835db8a82692ee24 to your computer and use it in GitHub Desktop.
package zio_grpc.examples.helloworld
import io.grpc.Status
import scalapb.zio_grpc.ServerMain
import scalapb.zio_grpc.ServiceList
import scalapb.zio_grpc.{RequestContext, ZTransform}
import zio._
import zio.console._
import zio.stream._
import io.grpc.examples.helloworld.helloworld.ZioHelloworld.ZGreeter
import io.grpc.examples.helloworld.helloworld.{HelloReply, HelloRequest}
object GreeterImpl extends ZGreeter[ZEnv, Any] {
def sayHello(
request: HelloRequest
): ZIO[zio.ZEnv, Status, HelloReply] =
putStrLn(s"Got request: $request") *>
ZIO.succeed(HelloReply(s"Hello, ${request.name}"))
}
class Logging[R] extends ZTransform[R, Status, R with Has[RequestContext]] {
def logCause(cause: Cause[Status]): URIO[Has[RequestContext], Unit] = ZIO.effectTotal(println("got error"))
def accessLog: URIO[Has[RequestContext], Unit] = ZIO.effectTotal(println("got request"))
override def effect[A](io: ZIO[R, Status, A]): ZIO[R with Has[RequestContext], Status, A] =
io.zipLeft(accessLog).tapCause(logCause)
override def stream[A](io: ZStream[R, Status, A]): ZStream[R with Has[RequestContext], Status, A] =
(io ++ ZStream.fromEffect(accessLog).drain).onError(logCause)
}
object HelloWorldServer extends ServerMain {
def services: ServiceList[zio.ZEnv] = ServiceList.add(GreeterImpl.transform(new Logging))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment