package store import ( "crypto/sha256" "fmt" "sync" "git.andreafazzi.eu/andrea/testhub/client" "git.andreafazzi.eu/andrea/testhub/models" ) type MemoryQuizHubCollectorStore struct { questions map[string]*models.Question answers map[string]*models.Answer tests map[uint]*models.Quiz lastQuizID uint questionAnswer map[string][]string testQuestion map[string]uint // A mutex is used to synchronize read/write access to the map lock sync.RWMutex } func NewMemoryQuizHubCollectorStore() *MemoryQuizHubCollectorStore { s := new(MemoryQuizHubCollectorStore) s.questions = make(map[string]*models.Question) s.answers = make(map[string]*models.Answer) s.tests = make(map[uint]*models.Quiz) return s } func (s *MemoryQuizHubCollectorStore) ReadAllQuizzes() ([]*models.Quiz, error) { result := make([]*models.Quiz, 0) for _, t := range s.tests { result = append(result, t) } return result, nil } func (s *MemoryQuizHubCollectorStore) CreateQuiz(r *client.CreateQuizRequest) *models.Quiz { questionID := hash(r.Question.Text) test := new(models.Quiz) q, ok := s.questions[questionID] if !ok { // if the question is not in the store add it s.questions[questionID] = &models.Question{ ID: questionID, Text: r.Question.Text, } q = s.questions[questionID] } // Populate Question field test.Question = q for _, answer := range r.Answers { // Calculate the hash from text answerID := hash(answer.Text) _, ok := s.answers[answerID] if !ok { // if the answer is not in the store add it s.answers[answerID] = &models.Answer{ ID: answerID, Text: answer.Text, } } if answer.Correct { test.Correct = s.answers[answerID] } test.Answers = append(test.Answers, s.answers[answerID]) } s.lastQuizID++ test.ID = s.lastQuizID s.tests[s.lastQuizID] = test return test } func hash(text string) string { return fmt.Sprintf("%x", sha256.Sum256([]byte(text))) }