memory.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package store
  2. import (
  3. "crypto/sha256"
  4. "fmt"
  5. "sync"
  6. "git.andreafazzi.eu/andrea/testhub/client"
  7. "git.andreafazzi.eu/andrea/testhub/models"
  8. )
  9. type MemoryQuizHubCollectorStore struct {
  10. questions map[string]*models.Question
  11. answers map[string]*models.Answer
  12. tests map[uint]*models.Quiz
  13. lastQuizID uint
  14. questionAnswer map[string][]string
  15. testQuestion map[string]uint
  16. // A mutex is used to synchronize read/write access to the map
  17. lock sync.RWMutex
  18. }
  19. func NewMemoryQuizHubCollectorStore() *MemoryQuizHubCollectorStore {
  20. s := new(MemoryQuizHubCollectorStore)
  21. s.questions = make(map[string]*models.Question)
  22. s.answers = make(map[string]*models.Answer)
  23. s.tests = make(map[uint]*models.Quiz)
  24. return s
  25. }
  26. func (s *MemoryQuizHubCollectorStore) ReadAllQuizzes() ([]*models.Quiz, error) {
  27. result := make([]*models.Quiz, 0)
  28. for _, t := range s.tests {
  29. result = append(result, t)
  30. }
  31. return result, nil
  32. }
  33. func (s *MemoryQuizHubCollectorStore) CreateQuiz(r *client.CreateQuizRequest) *models.Quiz {
  34. questionID := hash(r.Question.Text)
  35. test := new(models.Quiz)
  36. q, ok := s.questions[questionID]
  37. if !ok { // if the question is not in the store add it
  38. s.questions[questionID] = &models.Question{
  39. ID: questionID,
  40. Text: r.Question.Text,
  41. }
  42. q = s.questions[questionID]
  43. }
  44. // Populate Question field
  45. test.Question = q
  46. for _, answer := range r.Answers {
  47. // Calculate the hash from text
  48. answerID := hash(answer.Text)
  49. _, ok := s.answers[answerID]
  50. if !ok { // if the answer is not in the store add it
  51. s.answers[answerID] = &models.Answer{
  52. ID: answerID,
  53. Text: answer.Text,
  54. }
  55. }
  56. if answer.Correct {
  57. test.Correct = s.answers[answerID]
  58. }
  59. test.Answers = append(test.Answers, s.answers[answerID])
  60. }
  61. s.lastQuizID++
  62. test.ID = s.lastQuizID
  63. s.tests[s.lastQuizID] = test
  64. return test
  65. }
  66. func hash(text string) string {
  67. return fmt.Sprintf("%x", sha256.Sum256([]byte(text)))
  68. }