PageRenderTime 22ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/salat/src/main/solutions/whattodo/Domain.scala

http://github.com/olim7t/mongo-scala
Scala | 74 lines | 49 code | 23 blank | 2 comment | 0 complexity | e7c7f4bf204b29e4d2d38ac7cfa392b5 MD5 | raw file
  1. package whattodo
  2. import com.novus.salat.annotations.raw.Key
  3. import org.bson.types.ObjectId
  4. import org.joda.time.DateTime
  5. import com.novus.salat._
  6. import com.novus.salat.global._
  7. import com.mongodb.casbah.query.Imports._
  8. // Domain objects
  9. // Note: they need to be declared outside of the Domain trait because Salat doesn't serialize nested classes
  10. case class Event(name: String, description: String, sessions: List[EventSession] = List(), venue: Venue, updated: DateTime, _id: Option[ObjectId] = None)
  11. case class EventSession(showDateTimeStart: DateTime)
  12. case class Venue(name: String, way: String, pCode: String, town: String, transports: Option[Transports] = None)
  13. case class Transports(stations: List[Station])
  14. case class Station(@Key("type") stationType: Option[String], ligne: String, name: String, distance: Int)
  15. trait Domain {
  16. this: MongoClient =>
  17. val eventRepository: EventRepository
  18. class EventRepository {
  19. def findById(id: ObjectId): Option[Event] = mongoDb("events").findOneByID(id).map(dbToEvent)
  20. def save(event: Event): Event = {
  21. val dbObject = eventToDb(event)
  22. mongoDb("events").save(dbObject)
  23. dbToEvent(dbObject)
  24. }
  25. def removeById(id: ObjectId) = mongoDb("events").remove(MongoDBObject("_id" -> id))
  26. def count = mongoDb("events").size
  27. def countWithName(name: String) = mongoDb("events").count(MongoDBObject("name" -> name))
  28. def addSessionToEvent(eventId: ObjectId, session: EventSession) {
  29. val dbObject = sessionToDb(session)
  30. mongoDb("events").update(MongoDBObject("_id" -> eventId), $push("sessions" -> dbObject))
  31. }
  32. def renameByDate(date: DateTime, newName: String) {
  33. val startDate = date.withTime(0, 0, 0, 0)
  34. val endDate = startDate.plusDays(1)
  35. mongoDb("events").updateMulti(("sessions.showDateTimeStart" $gt startDate $lt endDate), $set("name" -> newName))
  36. }
  37. def findLast10By(town: String, descriptionContains: String) = {
  38. val descriptionRegexp = (".*" + descriptionContains + ".*").r
  39. val criteria =
  40. MongoDBObject("venue.town" -> town, "description" -> descriptionRegexp) ++
  41. ("updated" $exists true)
  42. mongoDb("events").find(criteria).
  43. sort(MongoDBObject("updated" -> -1)).
  44. limit(10).
  45. map(dbToEvent);
  46. }
  47. private def eventToDb(event: Event): DBObject = grater[Event].asDBObject(event)
  48. private def dbToEvent(dbObject: DBObject): Event = grater[Event].asObject(dbObject)
  49. private def sessionToDb(session: EventSession): DBObject = grater[EventSession].asDBObject(session)
  50. }
  51. }