I am working on a play 2.1 project and need some guidance on a scala design problem. For our application, a request context object which stores client information from the incoming request is needed at the model layer.
case class ClientContext(clientName: String)
object ClientContext {
def apply(request: Request) = {
new ClientContext(request.params("clientName")) //pseudo code
}
}
my model
object MyDAO {
def findAll(context: ClientContext) = { ... }
}
Then in our controller, we need to pass it into model's dao method:
object MyController extends Controller {
def index = Action { implicit request =>
val results = MyDAO.findAll(ClientContext(request))
Ok(results)
}
}
The implicit request
is provided by the Action
class (I suppose) The problem with this approach is that I need to write implicit request =>
and ClientContext(request)
for every controller action that calls MyDAO.findAll.
Is there a way to improve the code through an Action wrapper and implicit value? I would like to be able to declare context: ClientContext
as an implicit parameter in the MyDAO.findAll
method and write my actions in the following way:
object MyDAO {
def findAll(implicit context: ClientContext) = { ... }
}
def index = ActionWithContext {
val results = MyDAO.findAll
Ok(results)
}
Is it possible to write an ActionWithContext (method or object with an apply method) to achieve that? The closest I have now is the following
def ActionWithContext(action: ClientContext => Result) = {
Action { implicit request =>
action(ClientContext(request))
}
}
usage
def index = ActionWithContext { context =>
val results = MyDAO.findAll(context)
Ok(results)
}
Any suggestion to improve this design will be helpful. Thanks!
PS: Honestly I wouldn't even think about further simplifying the code if this is on Java, but since it's scala, I figured it might be good chance to learn some scala patterns.