PageRenderTime 44ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/play2/app/models/ProductRepository.scala

http://github.com/olim7t/mongo-scala
Scala | 51 lines | 40 code | 10 blank | 1 comment | 0 complexity | 9f8bc5c8e97b0fc2b77d1f69f4a70a85 MD5 | raw file
  1. package models
  2. import org.bson.types.ObjectId
  3. import com.mongodb.casbah.query.Imports._
  4. import com.mongodb.casbah.Imports.WriteConcern
  5. import com.mongodb.casbah.{MongoConnection, MongoDB}
  6. import com.novus.salat._
  7. import com.novus.salat.global._
  8. case class Product(
  9. brand: String,
  10. model: String,
  11. price: Int,
  12. reviews: List[Review] = List(),
  13. _id: Option[ObjectId] = None
  14. )
  15. case class Review(
  16. author: String,
  17. comment: String
  18. )
  19. object ProductRepository {
  20. private val products = MongoConnection()("test")("products")
  21. def all: Seq[Product] = products.find().map(fromDb).toSeq
  22. def byId(id: ObjectId): Option[Product] = products.findOneByID(id).map(fromDb)
  23. def save(product: Product) = {
  24. val dbo = toDb(product)
  25. products.save(dbo, WriteConcern.Safe)
  26. product._id match {
  27. case Some(_) => product
  28. case None =>
  29. val newId = dbo.as[ObjectId]("_id")
  30. product.copy(_id = Some(newId))
  31. }
  32. }
  33. def removeById(id: ObjectId) = products.remove(MongoDBObject("_id" -> id))
  34. // Customize Salat context
  35. implicit val ctx = new Context {
  36. val name = "Custom Context"
  37. override val typeHintStrategy = StringTypeHintStrategy(when = TypeHintFrequency.WhenNecessary)
  38. }
  39. private def fromDb(dbObject: DBObject): Product = grater[Product].asObject(dbObject)
  40. private def toDb(product: Product): DBObject = grater[Product].asDBObject(product)
  41. }