我'm working on an endpoint that I want to be non-blocking. The purpose of this endpoint is very simple i.e. write a document to a Mongo store. I'm在Play 2.5.x应用程序中使用官方MongoDB Scala Driver .
我的理解是MongoDB使用 toFuture()
方法支持Futures . Source
问题是我的控制器中的处理方法希望解析为 Future[Result]
类型 . 但是, onComplete
回调(或其他回调函数)仅返回类型 Unit
,从而导致编译错误 . 是否有任何替代模式用于这些情况?我有什么选择?
注意 - 我知道Play会在写入失败并自动抛出500时捕获异常 . 但在这种情况下,我想手动处理它
class WriteController extends Controller {
def writeSingleEvent = Action.async { implicit request =>
val mongo = mongoService.getMongoClient() // my mongoservice
val database_name: String = request.getQueryString("database").getOrElse("")
val collection_name: String = request.getQueryString("collection").getOrElse("")
if (database_name == "" || collection_name == "") {
Future(BadRequest("Must specify database and collection names"))
} else {
val database = mongo.getDatabase(database_name)
val collection = database.getCollection(collection_name)
val body = request.body.asJson.get.toString
val bsondocument = BsonDocument.apply(body)
val document = Document(bsondocument)
val insertFuture = collection.insertOne(document).toFuture()
insertFuture.onComplete {
case Success(_) => Future(Ok("Inserted"))
case Failure(_) => Future(InternalServerError)
}
}
}
2 回答
使用此而不是
onComplete
.onComplete
用于执行任何副作用操作 .根据您的尝试,您可能正在寻找transform方法: