PageRenderTime 70ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/example_provider/src/main/scala/event.scala

http://github.com/whiter4bbit/oauth
Scala | 64 lines | 56 code | 8 blank | 0 comment | 4 complexity | 95ec4feb95143d7b77d92c0f712e3fe7 MD5 | raw file
  1. package info.whiter4bbit.oauth.scalatra.example
  2. import com.mongodb.casbah.Imports._
  3. import org.slf4j.LoggerFactory
  4. import java.util.Date
  5. import scalaz._
  6. import Scalaz._
  7. trait EventMongoCollection {
  8. val events: MongoCollection
  9. }
  10. case class Event(val id: Option[String], val name: String, val description: String, val startDate: Date, val endDate: Date)
  11. trait EventService { self: EventMongoCollection =>
  12. val logger = LoggerFactory.getLogger(getClass)
  13. def add(event: Event, consumerKey: String): Validation[String, Event] = {
  14. if (self.events.find(MongoDBObject("name" -> event.name)).size == 0) {
  15. self.events.insert(MongoDBObject("name" -> event.name,
  16. "description" -> event.description,
  17. "startDate" -> event.startDate,
  18. "consumerKey" -> consumerKey,
  19. "endDate" -> event.endDate))
  20. self.events.last.getAs[ObjectId]("_id").map((id) => {
  21. Event(Some(id.toString), event.name, event.description, event.startDate, event.endDate).success
  22. }).getOrElse("Can't resolve last object id".fail)
  23. } else {
  24. ("There are exists event with name %s" format event.name).fail
  25. }
  26. }
  27. def mine(consumerKey: String): Validation[String, List[Event]] = {
  28. self.events.find(MongoDBObject("consumerKey" -> consumerKey)).map((event) => {
  29. for {
  30. id <- event.getAs[ObjectId]("_id");
  31. name <- event.getAs[String]("name");
  32. description <- event.getAs[String]("description");
  33. startDate <- event.getAs[java.util.Date]("startDate");
  34. endDate <- event.getAs[java.util.Date]("endDate")
  35. } yield {
  36. Event(Some(id.toString), name, description, startDate, endDate)
  37. }
  38. }).toList.filter(_.isDefined).map(_.get).success
  39. }
  40. def objectId(eventId: String): Option[ObjectId] = {
  41. try {
  42. Some(new ObjectId(eventId))
  43. } catch {
  44. case _ => None
  45. }
  46. }
  47. def attend(eventId: String, consumerKey: String): Validation[String, String] = {
  48. (for {
  49. id <- objectId(eventId);
  50. modified <- self.events.findAndModify(MongoDBObject("_id" -> id),
  51. MongoDBObject("$addToSet" -> MongoDBObject("attendees" -> consumerKey)))
  52. } yield {
  53. eventId.success
  54. }).getOrElse("Error while updating event".fail)
  55. }
  56. }