Skip to content

Instantly share code, notes, and snippets.

View adamw's full-sized avatar

Adam Warski adamw

View GitHub Profile
trait SttpBackend[F[_], +P] {
def send[T, R >: P with Effect[F]](request: Request[T, R]): F[Response[T]]
def close(): F[Unit]
def responseMonad: MonadError[F]
}
package sttp.client.examples
import monix.eval.Task
import sttp.client._
import sttp.client.asynchttpclient.monix.AsyncHttpClientMonixBackend
import sttp.ws.WebSocket
object WebSocketMonix extends App {
import monix.execution.Scheduler.Implicits.global
import zio._
object Main extends App {
override def run(args: List[String]): ZIO[zio.ZEnv, Nothing, ExitCode] = {
// instead of a method accessor, explicitly accessing the environment
val program: ZIO[Has[UserRegistration], Throwable, User] =
ZIO.accessM[Has[UserRegistration]](_.get.register(User("adam", "[email protected]")))
// the DB service is created using through layers (which wrap managed resources)
val dbLayer: ZLayer[Any, Throwable, DB] =
import zio._
object Main extends App {
override def run(args: List[String]): ZIO[zio.ZEnv, Nothing, ExitCode] = {
ConnectionPoolIntegration
.managedConnectionPool(DBConfig("jdbc://localhost"))
.use { cp =>
lazy val db = new RelationalDB(cp)
lazy val userModel = new DefaultUserModel(db)
lazy val userRegistration = new UserRegistration(DefaultUserNotifier, userModel)
import zio.Task
trait DB {
def execute(sql: String): Task[Unit]
}
class RelationalDB(cp: ConnectionPool) extends DB {
override def execute(sql: String): Task[Unit] =
Task {
println(s"Running: $sql, on: $cp")
import zio._
object Main extends App {
override def run(args: List[String]): ZIO[zio.ZEnv, Nothing, ExitCode] = {
// using the UserRegistration's method accessor to construct the program,
// outside of a layer definition
val program: ZIO[UserRegistration, Throwable, User] =
UserRegistration.register(User("adam", "[email protected]"))
// composing layers to create a DB instance
import zio.{Task, ZIO, ZLayer, ZManaged}
object DB {
// 1. service
trait Service {
def execute(sql: String): Task[Unit]
}
// 2. layer
val liveRelationalDB: ZLayer[HasConnectionPool, Throwable, DB] = ZLayer.fromService
import zio.{Task, ZIO, ZLayer}
object UserRegistration {
// 1. service
class Service(notifier: UserNotifier.Service, userModel: UserModel.Service) {
def register(u: User): Task[User] = {
for {
_ <- userModel.insert(u)
_ <- notifier.notify(u, "Welcome!")
} yield u
// UserModel.scala
import zio.{Task, ZIO, ZLayer}
object DB {
// 1. service
trait Service {
def execute(sql: String): Task[Unit]
}
// 2., 3. omitted here
package sttp.tapir.examples
import cats.arrow.FunctionK
import cats.data.OptionT
import izumi.reflect.Tag
import org.http4s._
import org.http4s.server.Router
import org.http4s.server.blaze.BlazeServerBuilder
import org.http4s.syntax.kleisli._
import zio.interop.catz._