PageRenderTime 41ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/scala/checklist/Database.scala

https://gitlab.com/williamhogman/checklist
Scala | 64 lines | 45 code | 19 blank | 0 comment | 2 complexity | 8bc7313dba2060eb8f42954d65e89426 MD5 | raw file
Possible License(s): Apache-2.0
  1. package checklist
  2. import com.mongodb.casbah.Imports._
  3. import org.bson.types.ObjectId
  4. object Database {
  5. val connection = MongoConnection()
  6. val db = connection("checklist_test")
  7. }
  8. trait DBRefable[T] {
  9. def ObjectId(): ObjectId
  10. def deref(): Option[T]
  11. }
  12. class DBRef[T: IdFindable](val id: ObjectId) extends DBRefable[T] {
  13. def ObjectId() = id
  14. def deref() = {
  15. val findable = implicitly[IdFindable[T]]
  16. findable.byId(id)
  17. }
  18. }
  19. trait MongoColMixin {
  20. protected def mdbcol : MongoCollection
  21. protected def find(query: MongoDBObject): Iterator[MongoDBObject] =
  22. mdbcol.find(query) map(wrapDBObj)
  23. protected def findOne(query: MongoDBObject) : Option[MongoDBObject] =
  24. mdbcol.findOne(query) map(wrapDBObj)
  25. protected def findOneById(id: ObjectId) =
  26. mdbcol.findOneByID(id)
  27. protected def update(query: MongoDBObject, to: MongoDBObject) =
  28. mdbcol.update(query, to)
  29. }
  30. trait IdFindable[T] {
  31. def byId(id: ObjectId): Option[T]
  32. }
  33. trait DBClientImp {
  34. def byId[T: IdFindable](id: ObjectId) = {
  35. val findable = implicitly[IdFindable[T]]
  36. findable.byId(id)
  37. }
  38. def byId[T: IdFindable](id: String): Option[T] =
  39. makeObjectId(id) flatMap(byId[T](_))
  40. private def makeObjectId(id: String): Option[ObjectId] =
  41. if (ObjectId.isValid(id)) Some(new ObjectId(id))
  42. else None
  43. }
  44. trait DBImplicits //extends TemplateImplicits with UserImplicits
  45. object DBClient extends DBClientImp