简体   繁体   中英

Play2 for Scala: is Action Chaining a missing feature?

Few days ago I run into an eventually missing feature of Play, that is Action Chaining. Here's what I mean:

I have a controller with two Actions, and I'd like to call an action from another action in order to stay DRY. My goal is to automatically sign a user in after he signs on.

object MyController extends Controller {

   def signOn = Action {
      // ... do stuff to sign the user on
      signIn  // call the next Action
   }


   def signIn = Action {
      // ... do stuff to sign the user in
      Ok("Welcome, Dude!") 
   } 
}

I've found this nice but outdated solution here (it's for Play 2.0.x)

http://www.natalinobusa.com/2012/07/chained-actions-in-play-framework-20.html

now I'm trying to write something similar on Play 2.2.x but I'd like to know if it is actually a missing feature and if some of you has already implemented something similar.

And finally: would you think it would be something nice to have in the framework?

What about doing it like this?

def signOn = Action.async { request => 
  // ... do stuff to sign the user on
  signIn(request)  // call the next Action
}

def signIn = Action {
  // ... do stuff to sign the user in
  Ok("Welcome, Dude!")
}

The solution proposed by Johan is what I was looking for. I ended up with this (nice?) solution for a neat chained action controller

package controllers

import play.api._
import play.api.mvc._

object TestCtrl extends Controller {

  def signOn = Action.async { request => 
  // ... do stuff to sign the user on
    if ( true ) 
      signIn(request)  // call the next Action
    else
      stopChaining( Ok("Stop") )(request)
  }

  def signIn = Action {
    // ... do stuff to sign the user in
    Ok("Welcome, Dude!")
  }

  private def stopChaining(result: SimpleResult) = Action {
    // ... do nothing, just return the result
    result
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM