/db/src/main/scala/uk/co/randomcoding/partsdb/db/mongo/MongoAllOrOneAccess.scala

https://github.com/jmrowe/PartsDbWebApp · Scala · 53 lines · 28 code · 7 blank · 18 comment · 1 complexity · 958c489902f3869a73bc50ad82b620a3 MD5 · raw file

  1. /**
  2. *
  3. */
  4. package uk.co.randomcoding.partsdb.db.mongo
  5. import com.mongodb.casbah.Imports._
  6. import uk.co.randomcoding.partsdb.db.mongo.MongoConverters._
  7. import uk.co.randomcoding.partsdb.core.id._
  8. import net.liftweb.common.Logger
  9. /**
  10. * @author RandomCoder <randomcoder@randomcoding.co.uk>
  11. *
  12. */
  13. trait MongoAllOrOneAccess extends Logger {
  14. /**
  15. * The '''`MongoCollection`''' that this trait will access
  16. */
  17. val collection: MongoCollection
  18. /**
  19. * Define a function that generates a query to get a specific item from the db
  20. */
  21. private val queryOne: (String, Identifier) => MongoDBObject = (idFieldName: String, idFieldValue: Identifier) => {
  22. val mongoIdentifier = MongoDBObject("id" -> idFieldValue.id)
  23. MongoDBObject(idFieldName -> mongoIdentifier)
  24. }
  25. /**
  26. * A function that generates a query that looks for all objects that have a specific id field.
  27. * As all objects have a field `addresId`, `partId` etc that is its unique identifier this
  28. * only requires the identifier exist by name.
  29. */
  30. private val queryAll = (idFieldName: String) => idFieldName $exists true
  31. def getOne[T <: AnyRef](idFieldName: String, id: Identifier)(implicit mf: Manifest[T]): Option[T] = {
  32. collection.findOne(queryOne(idFieldName, id)).toList match {
  33. case Nil => None
  34. case head :: Nil => Some(convertFromMongoDbObject(head))
  35. case head :: tail :: Nil => {
  36. error("Query for single item [%s] returned multiple objects. Returning first result only")
  37. Some(convertFromMongoDbObject(head))
  38. }
  39. }
  40. }
  41. def getAll[T <: AnyRef](idFieldName: String)(implicit mf: Manifest[T]): List[T] = {
  42. for (result <- collection.find(queryAll(idFieldName)).toList) yield {
  43. convertFromMongoDbObject(result)
  44. }
  45. }
  46. }