alwaysCache

Signature

def alwaysCache[K](cache: Cache[K, RouteResult], keyer: PartialFunction[RequestContext, K]): Directive0

Description

Like cache but disregards a Cache-Control request header.

Example

//Example keyer for non-authenticated GET requests
val simpleKeyer: PartialFunction[RequestContext, Uri] = {
  val isGet: RequestContext ⇒ Boolean = _.request.method == GET
  val isAuthorized: RequestContext ⇒ Boolean = _.request.headers.exists(_.is(Authorization.lowercaseName))
  PartialFunction {
    case r: RequestContext if isGet(r) && !isAuthorized(r) ⇒ r.request.uri
  }
}

var i = 0
val route =
  alwaysCache(routeCache, simpleKeyer) {
    complete {
      i += 1
      i.toString
    }
  }

Get("/") ~> route ~> check {
  responseAs[String] shouldEqual "1"
}
// now cached
Get("/") ~> route ~> check {
  responseAs[String] shouldEqual "1"
}
Get("/") ~> `Cache-Control`(`no-cache`) ~> route ~> check {
  responseAs[String] shouldEqual "1"
}
The source code for this page can be found here.