ReactiveMongo with Play-json responsibility's division

90 Views Asked by At

I'm using play-json to serialize my incoming jsons to case classes, for example from sqs source, or from api calls.

its a very simple class JsonSerialization that I import where I need it:

object JsonSerialization {
  implicit val StatusFormat: Format[Status] = EnumFormats.formats(Status)
  implicit val PersonFormat: OFormat[Person] = Json.format[Person]
}

but now I wonder, from what I understand in my Dao there needs to be something to serialize my case class to BSON , cause my Dao gets the case class, and when I fetch from something to de-serialize to my case class. I only imported in the Dao:

import reactivemongo.play.json.compat.json2bson.{toDocumentReader, toDocumentWriter}
import serializers.JsonSerialization._

and find and insert works perfectly,

  def insert(person: Person): Future[Person] = {
    val writeRes: Future[WriteResult] = collection.insert.one(person)

    writeRes.onComplete {
      case Failure(e) => e.printStackTrace()
      case Success(writeResult) =>
        logger.info(s"successfully inserted person")
    }

    writeRes map { _ => person }
  }


  def find(name: String): Future[Person] = {
    collection.find(BSONDocument(
      "name" -> name
    )).requireOne[Person]
  }

can you please tell me what part in charge of what in the Dao? I'm a bit confused

sorry if this a beginner question, but it will be helpful to get short explanation

1

There are 1 best solutions below

0
On

I am using Play framework 2.8 with ReactiveMongo 1.0. What I am doing usually is,

1. Do a find on a collection.

This will return some BSONDocuments and you need to provide the BSON readers and writers to convert the BSONDocuments to/from your case classes. You can see some tutorials and example here. Then, you can do some generic queries with the following code:

    for {
        c <- database.map(_.collection(collectionName))
        r <- c.find(selector.getOrElse(BSONDocument()), projection)
            .sort(sorter.getOrElse(BSONDocument()))
            .cursor[T]().collect[List](Int.MaxValue, Cursor.FailOnError[List[T]]())
    } yield r

2. Return the query result in JSON

When you have retrieved query result, you can return them in JSON with Json.toJson(), which will implicitly invokes the JSON readers/writers of the case classes.

Person.find().map {
    item => {
        Ok(Json.toJson(item))
    }
}

I did not use bson2json and I guess it help to convert case class to JSON behind the scene.