PageRenderTime 39ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

/questions/src/main/scala/com/cyrusinnovation/inquisition/questions/mongodb/MongoQuestionRepository.scala

https://github.com/cyrusinnovation/inquisition
Scala | 81 lines | 66 code | 15 blank | 0 comment | 1 complexity | b61972836eda7099ece251e18566f4fe MD5 | raw file
  1. package com.cyrusinnovation.inquisition.questions.mongodb
  2. import com.cyrusinnovation.inquisition.questions.{Question, QuestionRepository}
  3. import org.springframework.beans.factory.annotation.Autowired
  4. import com.novus.salat._
  5. import com.novus.salat.global._
  6. import org.springframework.stereotype.Repository
  7. import com.mongodb.casbah.Imports._
  8. @Repository
  9. class MongoQuestionRepository @Autowired()(db: MongoDB) extends QuestionRepository {
  10. val questions = db("questions")
  11. questions.ensureIndex(MongoDBObject("responses.id" -> 1))
  12. questions.ensureIndex(MongoDBObject("tags.name" -> 1))
  13. def save(question: Question): Question = {
  14. question.id match {
  15. case None => {
  16. val dbObj = grater[Question].asDBObject(question)
  17. questions.insert(dbObj, WriteConcern.Safe)
  18. question.copy(id = Some(dbObj("_id").toString))
  19. }
  20. case Some(id: String) => {
  21. val dbObj = grater[Question].asDBObject(question)
  22. questions.update(MongoDBObject("_id" -> new ObjectId(id)), dbObj, false, false, WriteConcern.Safe)
  23. question.copy(id = Some(dbObj("id").toString))
  24. }
  25. }
  26. }
  27. def db2question(dbObj: DBObject): Question = {
  28. val question = grater[Question].asObject(dbObj)
  29. question.copy(id = Some(dbObj("_id").toString))
  30. }
  31. def findById(id: String): Option[Question] = {
  32. val result: Option[DBObject] = questions.findOneByID(new ObjectId(id))
  33. result.map {
  34. db2question
  35. }
  36. }
  37. def findRecent(limit: Int): List[Question] = {
  38. val results = questions.find().limit(limit) map (db2question)
  39. results.toList
  40. }
  41. def findQuestionCount(): Int = {
  42. questions.count(x => true)
  43. }
  44. def deleteQuestion(id: String) {
  45. questions.remove(MongoDBObject("_id" -> new ObjectId(id)), WriteConcern.Safe)
  46. }
  47. def getClientList(startsWith: String, limit: Int): List[String] = {
  48. val clients = questions.distinct("client")
  49. .map(x => x.toString)
  50. .filter(_.toLowerCase.startsWith(startsWith.toLowerCase))
  51. .sortBy(x => x).toList
  52. if (limit <= 0) {
  53. return clients
  54. }
  55. clients.take(limit)
  56. }
  57. def findResponseQuestion(responseId: String): Option[Question] = {
  58. questions.findOne(MongoDBObject("responses.id" -> responseId))
  59. .map(db2question(_))
  60. .toList
  61. .headOption
  62. }
  63. def findQuestionsWithoutResponses(limit: Int): List[Question] = {
  64. questions.find("responses" $size 0).limit(limit).map(db2question).toList
  65. }
  66. }