Created
August 24, 2018 17:04
-
-
Save cb372/4bb9221ce68373894bc6f6ec1292d88f to your computer and use it in GitHub Desktop.
Conditional caching in ScalaCache
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
import scala.concurrent.ExecutionContext.Implicits.global | |
import scala.concurrent.Future | |
import scalacache._ | |
import scalacache.caffeine._ | |
import scalacache.modes.scalaFuture._ | |
type Error = String | |
type Token = Int | |
implicit val tokenCache: Cache[Token] = CaffeineCache[Token] | |
def fetchToken(credentials: String): Future[Either[Error, Token]] = { | |
if (credentials == "sesame") | |
Future.successful(Right(123)) | |
else | |
Future.successful(Left("nope")) | |
} | |
def handleCacheMiss(credentials: String): Future[Either[Error, Token]] = | |
for { | |
tokenOrError <- fetchToken(credentials) | |
_ <- tokenOrError match { | |
case Left(_) => Future.successful(()) // do not write to cache | |
case Right(token) => put(credentials)(token, ttl = None) // write to cache | |
} | |
} yield tokenOrError | |
def authenticate(credentials: String): Future[Either[Error, Token]] = | |
for { | |
cachedToken <- get(credentials) | |
result <- cachedToken match { | |
case Some(token) => Future.successful(Right(token)) | |
case None => handleCacheMiss(credentials) | |
} | |
} yield result | |
import scala.concurrent.Await | |
import scala.concurrent.duration.Duration | |
Await.result(authenticate("incorrect credentials"), Duration.Inf) | |
// res0: Either[Error,Token] = Left(nope) | |
Await.result(authenticate("sesame"), Duration.Inf) | |
// res1: Either[Error,Token] = Right(123) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment