Created
May 23, 2020 22:31
-
-
Save dkomanov/34fc1e317c1d11106d4377eb13c40af7 to your computer and use it in GitHub Desktop.
[writing-async-app-in-scala-part-2] RPC with caching
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
case class HttpRequest(uri: String) | |
def handleFromMemcached(r: HttpRequest): Future[Option[Int]] = { | |
require(r.uri != "/memcached-boom", "Memcached Boom!") | |
Future.successful(if (r.uri == "/memcached") Some(42) else None) | |
} | |
def handleFromCdn(r: HttpRequest): Future[Option[Int]] = { | |
require(r.uri != "/cnd-boom", "CDN Boom!") | |
Future.successful(if (r.uri == "/cdn") Some(42) else None) | |
} | |
def handleFromHadoop(r: HttpRequest): Future[Int] = | |
Future.successful(42) | |
def handle(r: HttpRequest): Future[Int] = { | |
// suppose here we're inside Future's execution lifecycle, so it's safe to throw exceptions. | |
handleFromMemcached(r) | |
.flatMap { memcachedResult => | |
memcachedResult.fold { | |
handleFromCdn(r).flatMap { cdnResult => | |
cdnResult.fold { | |
handleFromHadoop(r) | |
}(Future.successful) | |
} | |
}(Future.successful) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment