Created
September 20, 2021 21:05
-
-
Save otobrglez/e7048262d5f2638a29739b26c3fcc3db to your computer and use it in GitHub Desktop.
Playing around with caching with Cats Effect
This file contains 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
final case class SimpleCache() { | |
private def tempDir(key: String): IO[Path] = | |
IO.fromTry(Try(System.getProperty("java.io.tmpdir")).map(s => Paths.get(s, key))) | |
private def serialize[V](path: Path)(v: V): Unit = { | |
val out = new ObjectOutputStream(new FileOutputStream(path.toString)) | |
out.writeObject(v) | |
out.close() | |
} | |
private def deserialize[V](path: Path): V = { | |
val in = new ObjectInputStream(new FileInputStream(path.toString)) | |
val obj = in.readObject() | |
in.close() | |
obj.asInstanceOf[V] | |
} | |
def fetch[V](key: String)(f: => IO[V]): IO[V] = | |
for { | |
cachePath <- tempDir(s"cache-${key}") | |
result <- IO(cachePath.toFile.exists()).flatMap { | |
case true => | |
IO.println(s"Loading from path ${cachePath}") *> | |
IO(deserialize[V](cachePath)) | |
case false => | |
f.map { value => | |
serialize[V](cachePath)(value) | |
value | |
} | |
} | |
} yield result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment