2016-04-11 28 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)'? –

相关问题