testhub/store/memory.go

81 lines
1.8 KiB
Go
Raw Permalink Normal View History

2022-05-25 12:21:32 +02:00
package store
2022-05-25 18:09:54 +02:00
import (
2022-06-16 17:21:04 +02:00
"crypto/sha256"
"fmt"
2022-05-25 19:24:12 +02:00
"sync"
2022-05-25 18:09:54 +02:00
"git.andreafazzi.eu/andrea/testhub/models"
)
2022-06-17 16:02:58 +02:00
type MemoryQuizHubCollectorStore struct {
2022-06-16 17:21:04 +02:00
questions map[string]*models.Question
answers map[string]*models.Answer
2022-06-17 16:02:58 +02:00
tests map[uint]*models.Quiz
lastQuizID uint
2022-06-16 17:21:04 +02:00
questionAnswer map[string][]string
testQuestion map[string]uint
2022-05-25 19:24:12 +02:00
// A mutex is used to synchronize read/write access to the map
lock sync.RWMutex
}
2022-06-17 16:02:58 +02:00
func NewMemoryQuizHubCollectorStore() *MemoryQuizHubCollectorStore {
s := new(MemoryQuizHubCollectorStore)
2022-05-26 09:53:08 +02:00
2022-06-16 17:21:04 +02:00
s.questions = make(map[string]*models.Question)
s.answers = make(map[string]*models.Answer)
2022-06-17 16:02:58 +02:00
s.tests = make(map[uint]*models.Quiz)
2022-05-25 19:24:12 +02:00
return s
}
2022-06-17 16:02:58 +02:00
func (s *MemoryQuizHubCollectorStore) ReadAllQuizzes() ([]*models.Quiz, error) {
result := make([]*models.Quiz, 0)
2022-06-16 17:21:04 +02:00
for _, t := range s.tests {
result = append(result, t)
2022-05-26 09:53:08 +02:00
}
2022-06-17 16:02:58 +02:00
return result, nil
2022-05-25 12:21:32 +02:00
}
2022-06-17 16:02:58 +02:00
func (s *MemoryQuizHubCollectorStore) CreateQuiz(r *CreateQuizRequest) *models.Quiz {
2022-06-16 17:21:04 +02:00
questionID := hash(r.Question.Text)
2022-06-17 16:02:58 +02:00
test := new(models.Quiz)
2022-06-16 17:21:04 +02:00
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])
}
2022-06-17 16:02:58 +02:00
s.lastQuizID++
test.ID = s.lastQuizID
s.tests[s.lastQuizID] = test
2022-06-16 17:21:04 +02:00
return test
}
2022-05-25 19:24:12 +02:00
2022-06-16 17:21:04 +02:00
func hash(text string) string {
return fmt.Sprintf("%x", sha256.Sum256([]byte(text)))
2022-05-25 18:09:54 +02:00
}