Caching an action in a multi-language website using Play Framework's Cached API

天大地大妈咪最大 提交于 2019-11-30 11:03:00

Maybe the problem is in the getLanguage method. Try this, as recommended by the docs:

def getLanguage(request: RequestHeader): String = {
    request.acceptLanguages
           .map(_.code)
           .headOption
           .getOrElse(helpers.LanguageHelpers.FRENCH)
}

Also, take a look at Controller.request2lang() method and see if it could be helpful to you.

I do not know what is the issue you are facing but I did a small proof of concept and there is no issue at all.

package controllers

import play.api.cache.Cached
import play.api.mvc.{Action, Controller, EssentialAction, RequestHeader}

object Caches {
  import play.api.Play.current

  def cacheResponseFor(label: String, duration: Int)(action: EssentialAction) = {
    Cached({r: RequestHeader => label + getLanguage(r)}, duration){ action }
  }

  def getLanguage(request: RequestHeader): String = {
    request.cookies
      .get("language")
      .map(_.value)
      .getOrElse("fr")
  }
}

class CachedApplication () extends Controller {

  import Caches._

  def index = cacheResponseFor("homePage", 60) {
    Action { implicit req =>
      getLanguage(req) match {
        case "fr" =>
          Ok("Bonjour le monde")
        case _ =>
          Ok("Hello world")
      }
    }
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!