probo/store/memory/memory.go

59 lines
1.4 KiB
Go

package memory
import (
"errors"
"sync"
"git.andreafazzi.eu/andrea/probo/hasher"
"git.andreafazzi.eu/andrea/probo/models"
)
type MemoryProboCollectorStore struct {
// IDs maps
quizzes map[string]*models.Quiz
collections map[string]*models.Collection
participants map[string]*models.Participant
// Hashes maps
questionsHashes map[string]*models.Question
answersHashes map[string]*models.Answer
quizzesHashes map[string]*models.Quiz
hasher hasher.Hasher
// A mutex is used to synchronize read/write access to the map
lock sync.RWMutex
}
func NewMemoryProboCollectorStore(hasher hasher.Hasher) *MemoryProboCollectorStore {
s := new(MemoryProboCollectorStore)
s.hasher = hasher
s.questionsHashes = make(map[string]*models.Question)
s.answersHashes = make(map[string]*models.Answer)
s.quizzesHashes = make(map[string]*models.Quiz)
s.quizzes = make(map[string]*models.Quiz)
s.collections = make(map[string]*models.Collection)
s.participants = make(map[string]*models.Participant)
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")
}
// Check for duplicates
hashes := s.hasher.QuizHashes(r.Quiz)
quizHash := hashes[len(hashes)-1]
quiz := s.getQuizFromHash(quizHash)
if quiz != nil { // Quiz is already present in the store
return quiz, false, nil
}
}