PageRenderTime 51ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/app/models/MongoItem.scala

https://github.com/alessandroleite/lojinha
Scala | 52 lines | 36 code | 14 blank | 2 comment | 2 complexity | b20e0ee18b40fa57de9c7d2d87ba064c MD5 | raw file
  1. package models
  2. import com.mongodb.casbah.Imports._
  3. import com.mongodb.casbah.commons.MongoDBObject
  4. import com.novus.salat.dao.SalatDAO
  5. import play.api.Play.current
  6. import se.radley.plugin.salat._
  7. case class Sequence(id: ObjectId, name: String, lastValue: Int)
  8. object Sequence {
  9. val dao = new SalatDAO[Sequence, ObjectId](collection = mongoCollection("sequences")) {}
  10. def nextIntFor(name: String): Int = {
  11. val mongoObj = MongoDBObject("name" -> name)
  12. val value = dao.findOne(mongoObj).map(_.lastValue).getOrElse(0)
  13. dao.update(mongoObj, MongoDBObject("name" -> name, "lastValue" -> (value + 1)), true, false)
  14. value
  15. }
  16. }
  17. object MongoItemDAO extends ItemDAO {
  18. val dao = new SalatDAO[Item, Int](collection = mongoCollection("items")) {}
  19. def findById(id: Int): Option[Item] = dao.findOne(MongoDBObject("_id" -> id))
  20. def all(): List[Item] = dao.find(MongoDBObject.empty).toList
  21. def all(cat: String): List[Item] = dao.find(MongoDBObject("category" -> cat)).toList
  22. def create(name: String, description: String, imageKeys: Option[String]) =
  23. dao.insert(Item(Sequence.nextIntFor("items"), name, description, imageKeys))
  24. def delete(id: Long) = {}
  25. }
  26. //TODO: the current mapping causes items to be duplicated inside the bids
  27. // how to fix this, yet keeping the abstraction that supports both SQL and NoSQL ?
  28. object MongoBidDAO extends BidDAO {
  29. val dao = new SalatDAO[Bid, Int](collection = mongoCollection("bids")) {}
  30. def all(itemId: Int): List[Bid] = dao.find(MongoDBObject("item._id" -> itemId)).toList
  31. def highest(itemId: Int): Option[Bid] = dao.find(
  32. MongoDBObject("item._id" -> itemId)).foldLeft[Option[Bid]](None)((res, cur) => res match {
  33. case None => Some(cur)
  34. case Some(bid) => if (bid.value > cur.value) Some(bid) else Some(cur)
  35. }
  36. )
  37. def create(bid: Bid) = dao.insert(bid.copy(id = Sequence.nextIntFor("bids")))
  38. }