I am using play2.1 and I need a validator which checks if a given name is already taken or not in MongoDB. I am using reactive mongo which is an asynchronous MongoDB driver, although my question doesn't depend on this library.
Generally speaking, I would like to know what is the recommended approach of using asynchronous validation with play framework and scala?
Here is my code which I don't think is an elegant way of solving asynchronous validation:
Reads.verifying[String]{name=>
Await.result(coll.find(Json.obj("name"->name)).one[JsObject].map(_.isEmpty),Duration(1, SECONDS))
}
same pattern when using Reads[T] to validate a JsValue
notTaken=new Reads[JsValue]{
def reads(js:JsValue):JsResult[JsValue]={
val oid = js \ "_id"
Await.result(coll.find(Json.obj("_id"->oid)).one[JsObject].map(_.isEmpty),Duration(1, SECONDS)) match {
case true => JsSuccess(js)
case false => JsError("Object Id doesn't exist:"+Json.stringify(oid))
}
}
This code works but it doesn't look elegant/scalaish. Any alternative approaches to solve the above cases.