How to define default values ​​for optional fields in game form forms?

I am using web api using scala 2.0.2 playback platform. I would like to extract and check out a few get parameters. And for this, I use the "form" of the game, which allows me to define optional fields.

Problem: For these optional fields, I need to define a default value if the parameter is not passed. The code is designed to correctly analyze these three use cases:

  • / test? top = abc (error, abc is not an integer)
  • / test? top = 123 (valid, top is 123)
  • / test (valid, top is 42 (default))

I came up with the following code:

def test = Action { implicit request => case class CData(top:Int) val p = Form( mapping( "top" -> optional(number) )((top) => CData($top.getOrElse(42))) ((cdata:CData) => Some(Some(cdata.top))) ).bindFromRequest() Ok("all done.") } 

The code works, but it is definitely not elegant. There are many boiler tiles to set a default value for a missing query parameter.

Can someone suggest a cleaner and more consistent solution?

+6
source share
2 answers

on Play 2.1

  val p = Form (
     mapping (
       "top" -> default (number, 42)
     ) (CData.apply) (CData.unapply)
   ) .bindFromRequest ()

will do what you want.

+12
source

This is the job of the router to check query string parameters. Just define your parameter in the routes file:

 GET /test controllers.Application.test(top: Int ?= 42) 

And add top as a parameter to your controller method:

 def test(top: Int) = Action { // Use top here val data = CData(top) } 

Then Play will do the whole check. Notice how the default value is specified using ?= Syntax.

You should use forms only for POST requests.

Update:

If you want to manually check the parameters, then you can define a helper method:

 def getQueryParam(key: String, default: String)(implicit request: RequestHeader) = request.queryString.get(key).flatMap(_.headOption).getOrElse(default) 

And use it in your controller methods:

 def test = Action { implicit request => val top = getQueryParam("top", "42") ... 

But in doing so, you lose type checking. Of course, you can define helpers for each type, i.e. getIntParam , getStringParam , etc., but Play already contains a secure router implementation designed to solve such problems. I advise you to use a routing mechanism instead of a manual check.

+8
source

Source: https://habr.com/ru/post/919954/


All Articles