Skip to content

Instantly share code, notes, and snippets.

@loicdescotte
Last active January 19, 2024 09:03
Show Gist options
  • Save loicdescotte/1cc5f2a00506138a64efe3534214f6d7 to your computer and use it in GitHub Desktop.
Save loicdescotte/1cc5f2a00506138a64efe3534214f6d7 to your computer and use it in GitHub Desktop.
#ZIO Query #ZQuery caching
import zio._
import zio.query._
case class DbDepartment(id: Int, name: String)
case class DbEmployee(id: Int, name: String, departmentId: Int)
case class Employee(name: String, departmentName: String)
case class GetDepartement(id: Int) extends Request[Nothing, DbDepartment]
object ZqueryDemo extends ZIOAppDefault {
def run = {
val employees = for {
dbEmployees <- ZQuery.fromZIO(Repository.getAllEmployees)
// for each employee I want departement info, but I don't want to query multiple time for the same departement
employees <- ZQuery.foreachPar(dbEmployees)((e: DbEmployee) => {
val department = ZQuery.fromRequest(GetDepartement(e.departmentId))(Repository.datasource)
department.map(d => Employee(e.name, d.name))
})
} yield employees
for {
result <- employees.run
_ <- ZIO.foreach(result)((e: Employee) => Console.printLine(e.toString))
} yield ()
}
}
object Repository {
val datasource: DataSource[Any, GetDepartement] = DataSource.fromFunctionZIO("GetDepartement")((request: GetDepartement) => getDepartmentById(request.id))
def getDepartmentById(id: Int) = {
println("DB query : get department for dep Id " + id)
ZIO.succeed(id match {
case 1 => DbDepartment(1, "HR")
case _ => DbDepartment(2, "IT")
})
}
def getAllEmployees = {
println("DB query : get all employees")
ZIO.succeed(List(
DbEmployee(1, "John", 1),
DbEmployee(2, "Jane", 1),
DbEmployee(3, "Bob", 2)
))
}
}
/* Output :
DB query : get all employees
DB query : get department for dep Id 2
DB query : get department for dep Id 1
Employee(John,HR)
Employee(Jane,HR)
Employee(Bob,IT)
Dept 1 is returned 2 times but query is only run one time (cached)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment