Skip to content

Instantly share code, notes, and snippets.

@cb372
Created August 24, 2018 17:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cb372/4bb9221ce68373894bc6f6ec1292d88f to your computer and use it in GitHub Desktop.
Save cb372/4bb9221ce68373894bc6f6ec1292d88f to your computer and use it in GitHub Desktop.
Conditional caching in ScalaCache
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