Asynchronous input validators in Play2

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.

+4
source share
1 answer

Waiting blocks the request flow, if you are fine with this (and configure the game accordingly), then your solution is fine, but it probably won't be considered best practice.

I would move this check to the logic of your controller and do this asynchronous action, think of it more as a business logic than a failure, because it interacts with your database.

0
source

Source: https://habr.com/ru/post/1500015/


All Articles