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

后端 未结 2 1353
闹比i
闹比i 2021-01-01 15:32

In order to cache actions per label and language for a given number of seconds, I wrote the following helper method (where label, is the name I give to my action):



        
相关标签:
2条回答
  • 2021-01-01 16:07

    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")
          }
        }
      }
    }
    
    0 讨论(0)
  • 2021-01-01 16:10

    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.

    0 讨论(0)
提交回复
热议问题