Last active
June 4, 2020 05:20
-
-
Save adamw/eceaa5a141c4619effd0f5f4961c7899 to your computer and use it in GitHub Desktop.
This file contains hidden or 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.{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 | |
{ cp => new Service { | |
override def execute(sql: String): Task[Unit] = | |
Task(println(s"Running: $sql, on: $cp")) | |
} } | |
} | |
// 1. procedural, low-level interface | |
class ConnectionPool(url: String) { | |
def close(): Unit = () | |
override def toString: String = s"ConnectionPool($url)" | |
} | |
// 2. integration with ZIO | |
object ConnectionPoolIntegration { | |
def createConnectionPool(cfg: DBConfig): ZIO[Any, Throwable, ConnectionPool] = | |
ZIO.effect(new ConnectionPool(cfg.url)) | |
val closeConnectionPool: ConnectionPool => ZIO[Any, Nothing, Unit] = | |
(cp: ConnectionPool) => ZIO.effect(cp.close()).catchAll(_ => ZIO.unit) | |
def managedConnectionPool(cfg: DBConfig): ZManaged[Any, Throwable, ConnectionPool] = | |
ZManaged.make(createConnectionPool(cfg))(closeConnectionPool) | |
val live: ZLayer[HasDBConfig, Throwable, HasConnectionPool] = | |
ZLayer.fromServiceManaged(managedConnectionPool) | |
} | |
// --- | |
// 4. type aliases in package.scala | |
type HasDBConfig = Has[DBConfig] | |
type HasConnectionPool = Has[ConnectionPool] | |
type DB = Has[DB.Service] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment