PageRenderTime 41ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/questions/src/main/scala/com/cyrusinnovation/inquisition/response/mongodb/MongoResponseRepository.scala

https://github.com/cyrusinnovation/inquisition
Scala | 80 lines | 72 code | 8 blank | 0 comment | 3 complexity | 0495076b80411d99c767a9b0e818eddd MD5 | raw file
  1. package com.cyrusinnovation.inquisition.response.mongodb
  2. import com.cyrusinnovation.inquisition.questions.Question
  3. import com.cyrusinnovation.inquisition.response.{Response, ResponseRepository}
  4. import com.mongodb.casbah.MongoDB
  5. import org.springframework.beans.factory.annotation.Autowired
  6. import com.mongodb.casbah.commons.MongoDBObject
  7. import org.springframework.stereotype.Repository
  8. import com.cyrusinnovation.inquisition.questions.mongodb.MongoQuestionRepository
  9. import org.bson.types.ObjectId
  10. import java.lang.IllegalArgumentException
  11. @Repository
  12. class MongoResponseRepository @Autowired()(db: MongoDB, questionRepository: MongoQuestionRepository) extends ResponseRepository {
  13. def generateIdIfEmpty(response: Response): Response = {
  14. val responseId = response.id match {
  15. case None => {
  16. Some(new ObjectId().toStringMongod)
  17. }
  18. case Some(id: String) => {
  19. Some(id)
  20. }
  21. }
  22. response.copy(id = responseId)
  23. }
  24. def save(questionId: String, response: Response): Response = {
  25. questionRepository.findById(questionId) match {
  26. case None => {
  27. throw new IllegalArgumentException()
  28. }
  29. case Some(question: Question) => {
  30. val updatedResponse = generateIdIfEmpty(response)
  31. questionRepository.save(question.copy(responses = updatedResponse :: question.responses))
  32. updatedResponse
  33. }
  34. }
  35. }
  36. def updateResponse(response: Response): Response = {
  37. if (response.id.isEmpty) {
  38. throw new IllegalArgumentException()
  39. }
  40. getResponse(response.id.get) match {
  41. case None => {
  42. throw new IllegalArgumentException()
  43. }
  44. case Some((q, r)) => {
  45. val responses = q.responses.filter(x => x.id != response.id)
  46. questionRepository.save(q.copy(responses = response :: responses))
  47. response
  48. }
  49. }
  50. }
  51. def deleteResponse(responseId: String) = null
  52. def getResponse(responseId: String): Option[(Question, Response)] = {
  53. questionRepository.findResponseQuestion(responseId) match {
  54. case Some(x: Question) => {
  55. val response = x.responses
  56. .filter(_.id == Some(new ObjectId(responseId)))
  57. .headOption match {
  58. case None => {
  59. return Option.empty
  60. }
  61. case Some(y: Response) => {
  62. y
  63. }
  64. }
  65. Some((x, response))
  66. }
  67. case None => {
  68. Option.empty
  69. }
  70. }
  71. }
  72. }