I am using play2.1 and I need a validator that checks if a given name is accepted or not in MongoDB. I use reactive mongo, which is the MongoDB asynchronous driver, although my question is independent of this library.
Generally speaking, I would like to know what is the recommended approach of using asynchronous validation with the play card and scala?
Here is my code, which I don't think is an elegant way to solve 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 test 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 does not look elegant / scalaish. Any alternative approaches to solving the above cases.
source share