Play Framework / Scala: abstract repository and Json de/serialization -


this question maybe more scala play, here is: trying achieve abstraction of repository common db operations.

trait entity {   def id: uuid }  trait repository[t <: entity] {    val json_key_id = "_id"    def collection: jsoncollection    def insert(t: t): future[either[string, t]] = {     collection.insert(t).map(wr => if (wr.ok) right(t) else left(wr.getmessage()))       .recover { case t => left(t.getmessage) }   }     def update(t: t): future[either[string, t]] = {     val selector = json.obj(json_key_id -> t.id.tostring)     collection.update(selector, t).map(wr => if (wr.ok) right(t) else left(wr.getmessage()))       .recover { case t => left(t.getmessage) }   } } 

then have objects use with:

case class userdao(id: uuid) extends entity[userdao]  object userdao {   val json_key_id = "_id"    implicit val userdaowrites: owrites[userdao] = new owrites[userdao] {     def writes(user: userdao): jsobject = json.obj(       json_key_id -> jsstring(user.id.tostring)     )   }    implicit val userdaoreads: reads[userdao] = (     (__ \ json_key_id).read[uuid]     )(userdao.apply _) } 

and define repository this:

class userrepository @inject()(val reactivemongoapi: reactivemongoapi) extends repository[userdao] {   val db = reactivemongoapi.db   override def collection: jsoncollection = db.collection[jsoncollection]("users") } 

the error

no json serializer jsobject found type t. try implement implicit owrites or oformat type. collection.insert(t).map(wr => if (wr.ok) right(t) else left(wr.getmessage()))                  ^ 

i tried provide implicit owrites[t], or implicit owrites[_] no avail. maybe trying achieve impossible. if not, how solve this? thank much.

you should able use context bound.

trait entity {   def id: uuid }  class repository[t <: entity : writes] {   ... } 

that ensure if there exists implicit writes[t] in scope, available insert , update functions.


Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -