2016-04-11 27 views
0

我想構建一個簡單的RESTful服務,對數據庫執行CRUD操作並返回JSON。我有一個服務秉承的API這樣油滑 - 如果數據庫不包含結果怎麼辦

GET mydomain.com/predictions/some%20string 

我用它包含了我創建對象的關聯預測如下方法的DAO:

def getPrediction(rawText: String): Prediction = { 
    val predictionAction = predictions.filter{_.rawText === rawText}.result 
    val header = predictionAction.head 
    val f = db.run(header) 
    f.onComplete{case pred => pred} 
    throw new Exception("Oops") 
} 

但是,這不能成爲對,所以我開始閱讀有關Option。我相應地更改了我的代碼:

def getPrediction(rawText: String): Option[Prediction] = { 
    val predictionAction = predictions.filter{_.rawText === rawText}.result 
    val header = predictionAction.headOption 
    val f = db.run(header) 
    f.onSuccess{case pred => pred} 
    None 
} 

這仍然不太合適。調用這些過濾器,返回結果並處理任何不確定性的最佳方法是什麼?

+0

哪個版本的浮油? – marcospereira

+0

@marcospereira'3.1.1'。我想我通過添加'return Some(red)'和'return None'來計算出來。我讀了一些關於'Option'的文章,並使用'.isEmpty'來決定做什麼。儘管文檔看起來很模糊,但我仍然對使用'Slick'的最佳方式感到好奇。例如,還有'DBIO'序列。不確定哪個最適合使用。 –

回答

1

我想重寫代碼的最佳方式是這樣的:

def getPrediction(rawText: String): Future[Option[Prediction]] = { 
    db.run(users.filter(_.rawText === rawText).result.headOption) 
} 

換句話說,返回Future,而不是簡單的結果。這樣,數據庫操作將異步執行,這對於Play和Akka都是首選。

然後客戶端代碼將與Future一起使用。每個實例,Play操作會是這樣的:

def prediction = Action.async { 
    predictionDao.getPrediction("some string").map { pred => 
    Ok(views.html.predictions.show(pred)) 
    }.recover { 
    case ex => 
     logger.error(ex) 
     BadRequest() 
    } 
} 
+0

你的建議真的清理了我的dao api,所以謝謝。我實際上使用Spray,所以我在'onComplete'方面遇到了一些麻煩,但是我終於在工作中獲得了工作並學到了很多關於Futures的知識。另外,如果'_.rawText =='是'_.rawText ==='? –

+0

@BrianVanover根據您的評論作出了小的更正。此外,請隨時編輯答案,並添加如何使用Spray使用dao方法。 ;-) – marcospereira

+0

@marcospereira爲什麼不直接寫'db.run(users.filter(_。rawText === rawText).result.headOption)'? –

相關問題