/router/router/src/main/scala/uk/gov/gds/router/repository/MongoRepository.scala

https://github.com/alphagov/scala-router · Scala · 91 lines · 71 code · 20 blank · 0 comment · 4 complexity · f486f0f0ebe4163ee7a6d89b481d95c4 MD5 · raw file

  1. package uk.gov.gds.router.repository
  2. import uk.gov.gds.router.mongodb.MongoDatabase._
  3. import com.mongodb.DBObject
  4. import com.novus.salat._
  5. import com.novus.salat.global.NoTypeHints
  6. import com.mongodb.casbah.Imports._
  7. import uk.gov.gds.router.model._
  8. import uk.gov.gds.router.util.Logging
  9. import com.mongodb.casbah.commons.MongoDBObjectBuilder
  10. abstract class MongoRepository[A <: CaseClass with HasIdentity](collectionName: String, idProperty: String)(implicit m: Manifest[A])
  11. extends Repository[A] with MongoIndexTypes with Logging {
  12. protected val collection = getCollection(collectionName)
  13. private implicit val ctx = NoTypeHints
  14. createIndexes()
  15. protected implicit def domainObj2mongoObj(o: A) = grater[A].asDBObject(o)
  16. protected implicit def mongoObj2DomainObj(o: Option[collection.T]) = o map (grater[A].asObject(_))
  17. protected implicit def listOfMongoObjects2listOfDomainObjects(l: List[DBObject]) = l map (grater[A].asObject(_))
  18. protected def addIndex(index: DBObject, unique: Boolean, sparse: Boolean) =
  19. collection.underlying.ensureIndex(index, MongoDBObject(
  20. "unique" -> unique,
  21. "background" -> true,
  22. "sparse" -> sparse))
  23. protected def createIndexes() {
  24. addIndex(
  25. MongoDBObject(idProperty -> Ascending.order),
  26. Enforced.uniqueness,
  27. Complete.index)
  28. }
  29. def store(obj: A) = load(obj.id) match {
  30. case Some(_) =>
  31. Conflict
  32. case None =>
  33. collection += obj
  34. NewlyCreated
  35. }
  36. def load(id: String) = {
  37. collection.findOne(MongoDBObject(idProperty -> id))
  38. }
  39. def delete(id: String) = load(id) match {
  40. case Some(route) =>
  41. collection -= MongoDBObject(idProperty -> id)
  42. Deleted
  43. case None => NotFound
  44. }
  45. def simpleAtomicUpdate(id: String, params: Map[String, Any]) = {
  46. val builder = MongoDBObject.newBuilder
  47. for ((k, v) <- params) {
  48. if (v.isInstanceOf[Map[String, String]]) {
  49. addMapToQuery(k, v.asInstanceOf[Map[String, String]], builder)
  50. }
  51. else {
  52. builder += k -> v
  53. }
  54. }
  55. val updateResult = collection.findAndModify(
  56. query = MongoDBObject(idProperty -> id),
  57. update = MongoDBObject("$set" -> builder.result.asDBObject))
  58. updateResult match {
  59. case Some(_) => Updated
  60. case None => NotFound
  61. }
  62. }
  63. private def addMapToQuery(property: String, map: Map[String, String], query: MongoDBObjectBuilder) {
  64. val builder = MongoDBObject.newBuilder
  65. for ((k, v) <- map) {
  66. builder += k -> v
  67. query += property -> builder.result().asDBObject
  68. }
  69. }
  70. def all = collection.find().toList
  71. }