MongoDB Play Action calls

Play 2.7 Actions are Futures. MongoDB Scala drivers return futures as well. Prior versions of Play had Action.async and Action synchronous calls. So how do you handle MongoDB Futures within Play 2.7 Action calls ?

Reactive Mongodb DAO query returns Future[Future[RESULT]] .
You will have to flatten that to convert Future[RESULT], Then call it within Action.async{ }

Reactive MongoDB returns Future and not Future[Result]
I was able to get around this issue using Action.async.

I have MongoDB calls integrated with Action.async. Now I have an issue with authentication.
Before I could write a class to override invokeBlock to authenticate requests and inject it in. However calls to controllers do not seem to invoke this call when I use async. It works without async.
Is there a way to write custom Actions - async where I can authenticate the user using values in session ?

This was query result. Not play api Result. I just represented your intended type result from query that is why all are in Caps.

You can show us your code or you can follow this api-
https://www.playframework.com/documentation/2.7.x/api/scala/play/api/mvc/ActionBuilderImpl.html

I have the following Authentication code
class AuthenticatedAction @Inject() (parser: BodyParsers.Default)
(implicit ec: ExecutionContext) extends ActionBuilderImpl(parser) {
override def invokeBlock[A](request: Request[A],
block: (Request[A]) => Future[Result]) = {
private val logger = play.api.Logger(this.getClass)
logger.info(“Inside AuthenticatedUserAction::invokeBlock”)
block(request)
}
and I have a class which uses this authentication
@Singleton
class CharityCtrl @Inject()(config: Configuration,
cc: ControllerComponents,
authenticate: AuthenticatedAction,
charityService:CharityService)
extends AbstractController(cc) {

def getCharities = Action.async { implicit request =>

returns Future results from MongoDB

If I use authenticated.async { implicit =>

Authenticated.authenticate is not invoked but Future results from MongoDB are returned since it’s using ActionBuilderImpl.async

I need to authenticate when authenticated.async is called. How can I do this since ActionBuilderImpl.async is final.

Thank you

Thanks for the hint. After looking at the code for ActionBuilderImpl, I was able to write another function in my authentication class to call sync function.

1 Like