2016-12-15 79 views
-1

空的情況下,我有以下POST體的例子:處理中階遊戲框架

{ "Id": "123abxy"} 

{ "customUrl": "http://www.whiskey.com","Id": "123abxy"} 

{ "size": "88", "customUrl": "http://www.whiskey.com","Id": "123abxy"} 

與以下端點:

case class aType(
    customUrl: Option[String], 
    Id:Option[String], 
    size:Option[String] 
) 

@ResponseBody 
    def addCompany(
    @RequestBody a: aType, 
    @ModelAttribute("action-context") actionContext: ActionContext 
): DeferredResult[Created] = Action[Created] 
{ 

    val customUrl = { 
     a.customUrl 
    } 

    val size = { 
     if (a.size == None) {None} 
     else Option(a.size.get.toLong) 
    } 

    val Id = { 
      a.Id 
    } 

    val handle = register(
     customUrl, 
     Id, 
     size 
    ).run() 

    }.runForSpring[Nothing](executors, actionContext) 

另外:

def register(
    customUrl: Option[String], 
    Id: Option[String], 
    size: Option[Long] 
) 

鑑於上述情況,我想知道正確的方法來處理sizecustomUrl未傳遞int的情況o POST正文。

在這種情況下,由於size可以是一個值(Long)或nullcustomUrl可以是Stringnull,我將承擔適當的數據類型來處理,這將是Option[String]Option[Long]customUrlsize,分別。

我的問題是如何改變if-else條款來處理null或上述情景String/Long,這樣我就可以通過有效的變量進入register(..)功能?

乾杯,

回答

0

如果register函數接收大小和customURL作爲選項,有什麼問題呢?

我會做這樣的事情:

@ResponseBody 
    def addCompany(
    @RequestBody a: aType, 
    @ModelAttribute("action-context") actionContext: ActionContext 
): DeferredResult[Created] = Action[Created] 
{ 
    val handle = register(a.customUrl,a.id,a.size).run() 

    }.runForSpring[Nothing](executors, actionContext) 

如果返回None如果size沒有定義,那麼一個要求:

@ResponseBody 
     def addCompany(
     @RequestBody a: aType, 
     @ModelAttribute("action-context") actionContext: ActionContext 
    ): DeferredResult[Created] = Action[Created] 
    { 

     val sizeOpt = a.size 

     val handle =sizeOpt.map { size => 
      register(a.customUrl,a.id,Some(size)).run() 
     } 

     }.runForSpring[Nothing](executors, actionContext) 

但即使是更好的,將是你的寄存器功能不期望Option s,並只處理原始類型。然後,你只需要映射3個可選值(我推薦使用的理解):

for { 
    size <- a.size 
    url <- a.customUrl 
    id <- a.id 
} yield register(url, id, size).run() 

與寄存器定義爲:

def register(
    customUrl:String, 
    Id: String, 
    size: Long 
)