ReactiveMongo outside Controller

Leon Maia ⌘
The Journal by Leon Maia
2 min readAug 16, 2013

--

One thing that caught my attention when I began to use ReactiveMongo was functions like this called inside my controller:

def index(page: Option[Int] = None,
itemsPerPage: Option[Int] = None) = Action.async { request =>
// some business logic
db.command(Count(collection.name, Some(query)))
}

Sometimes is even worse, I don’t feel pleased to have this kind of code on my controller, so on every app, I start I’m following the following tactic.

trait Repository {
def remove(anything: Anything): Future[Unit]
def find(id: UUID): Future[Option[Anything]]
def list(page: Option[Int] = None,
itemsPerPage: Option[Int] = None): Future[List[Anything]]
def insert(anything: Anything): Future[UUID]
def update(anything: Anything): Future[Unit]
}

At this point we need to choose: easy way or BSON way, let’s go with the easy one :)

class MongoRepository(collection: JSONCollection) extends Repository {
// Here we implement all the methods
}

Wait! There’s still one thing left to do, our repository needs a JSONCollection, let’s create now an class to do the connection for us.

import reactivemongo.api._
import reactivemongo.api.DefaultDB
import scala.concurrent.ExecutionContext.Implicits.global

class MongoDBConnection {
val driver = new MongoDriver
val connection = driver.connection(List("localhost"))
val db = connection("db_name")
val collection = db.collection[JSONCollection]("collection_name")
}

This is how our controller will look after these modifications:

def index(page: Option[Int] = None,
itemsPerPage: Option[Int] = None) = Action.async { request =>
// some business logic
repository.list(page, itemsPerPage)
}

--

--

Software Engineer at Zendesk. In the past worked helping to build the architecture of Globo’s video streaming platform. Visit my blog: https://leonmaia.me