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

https://github.com/jmrowe/PartsDbWebApp · Scala · 46 lines · 29 code · 5 blank · 12 comment · 0 complexity · 9ef3671c37d2978a4e96df4a45c51f55 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.Identifier
  8. /**
  9. * @author RandomCoder <randomcoder@randomcoding.co.uk>
  10. *
  11. */
  12. trait MongoIdentifierAccess {
  13. val collection: MongoCollection
  14. private val incrementUniqueId = (currentId: Long) => {
  15. val newIdObject = MongoDBObject("uniqueId" -> (currentId + 1))
  16. val findIdObjectQuery = "uniqueId" $exists true
  17. collection.findOne(findIdObjectQuery) match {
  18. case None => collection += newIdObject
  19. case _ => collection.findAndModify(findIdObjectQuery, newIdObject)
  20. }
  21. }
  22. private val idQuery = "uniqueId" $exists true
  23. /**
  24. * Gets the next value for the unique id.
  25. *
  26. * This also increments the current value that is stored in the database
  27. */
  28. def nextId(): Long = {
  29. val findOneQuery = collection.findOne(idQuery)
  30. val idValue = findOneQuery match {
  31. case None => {
  32. 0
  33. }
  34. case Some(v) => {
  35. v.as[Long]("uniqueId")
  36. }
  37. }
  38. incrementUniqueId(idValue)
  39. idValue
  40. }
  41. }