probo/store/memory/memory.go

60 lines
1.4 KiB
Go
Raw Normal View History

2022-06-24 18:56:06 +02:00
package memory
import (
2023-10-07 11:43:12 +02:00
"errors"
2022-06-24 18:56:06 +02:00
"sync"
"git.andreafazzi.eu/andrea/probo/hasher"
"git.andreafazzi.eu/andrea/probo/models"
)
2022-06-29 16:08:55 +02:00
type MemoryProboCollectorStore struct {
// IDs maps
quizzes map[string]*models.Quiz
collections map[string]*models.Collection
participants map[string]*models.Participant
// Hashes maps
2022-06-29 16:08:55 +02:00
questionsHashes map[string]*models.Question
answersHashes map[string]*models.Answer
quizzesHashes map[string]*models.Quiz
hasher hasher.Hasher
2022-06-24 18:56:06 +02:00
// A mutex is used to synchronize read/write access to the map
lock sync.RWMutex
}
2022-06-29 16:08:55 +02:00
func NewMemoryProboCollectorStore(hasher hasher.Hasher) *MemoryProboCollectorStore {
s := new(MemoryProboCollectorStore)
2022-06-24 18:56:06 +02:00
s.hasher = hasher
2022-06-29 16:08:55 +02:00
s.questionsHashes = make(map[string]*models.Question)
s.answersHashes = make(map[string]*models.Answer)
s.quizzesHashes = make(map[string]*models.Quiz)
2022-06-24 18:56:06 +02:00
s.quizzes = make(map[string]*models.Quiz)
2023-10-07 11:43:12 +02:00
s.collections = make(map[string]*models.Collection)
s.participants = make(map[string]*models.Participant)
2022-06-24 18:56:06 +02:00
return s
}
func Create[T any](s *MemoryProboCollectorStore, elem *T) (*T, error) {
if elem == nil {
return nil, errors.New("A creation request was made passing a nil element")
2023-10-28 20:50:06 +02:00
}
2023-07-10 13:23:46 +02:00
// Check for duplicates
2022-06-28 13:49:35 +02:00
hashes := s.hasher.QuizHashes(r.Quiz)
quizHash := hashes[len(hashes)-1]
2022-06-29 16:08:55 +02:00
quiz := s.getQuizFromHash(quizHash)
2022-06-28 13:49:35 +02:00
if quiz != nil { // Quiz is already present in the store
return quiz, false, nil
2022-06-28 13:49:35 +02:00
}
2023-10-07 11:43:12 +02:00
}