What is the idomatic way to add headers to some, but not all results in Play 2.7?

49 views Asked by At

Let's say I have a very simple action;

About 50% of my routes will want to set the "as("text/csv") header. I'd like to have a single AsCSV action which just appends that header...

def simples: Action[AnyContent] = Action.async{Ok(someCSVdata).as("text/csv")}

I want to somehow extend action, so that I have something like a csvAction.

def simples: Action[AnyContent] = csvAction{Ok(someCSVdata)}

However, I'm lost in ActionBuilders, Refiners - filters...

Is there a simple way to do this?

1

There are 1 answers

0
Rodo On

I think this way it could work:

  def okCsvAction[A](action: Request[A] => Future[Result]) =
    Action.async(parse.empty) { implicit request =>
      action(request).map(_.as("text/csv"))
    }

  def someCSVdata = ???

  def simples = okCsvAction { implicit request =>
    Future.successful(Ok(someCSVdata))
  }

if we place it in a much better trait, something very similar to this to extract predetermined actions we can find here: https://github.com/adrianhurt/play-api-rest-seed