2023-12-12 09:22:07 +01:00
|
|
|
package store
|
|
|
|
|
2024-05-12 10:15:48 +02:00
|
|
|
import (
|
|
|
|
"fmt"
|
2023-12-12 09:22:07 +01:00
|
|
|
|
2024-05-12 10:15:48 +02:00
|
|
|
"git.andreafazzi.eu/andrea/probo/pkg/models"
|
|
|
|
)
|
|
|
|
|
|
|
|
type SessionStore struct {
|
|
|
|
*Store[*models.Session]
|
|
|
|
}
|
|
|
|
|
|
|
|
type ErrSessionAlreadyPresent struct {
|
|
|
|
hash string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *ErrSessionAlreadyPresent) Error() string {
|
|
|
|
return fmt.Sprintf("Session with hash %v is already present in the store.", e.hash)
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewSessionStore() *SessionStore {
|
|
|
|
return &SessionStore{
|
|
|
|
Store: NewStore[*models.Session](),
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *SessionStore) Create(session *models.Session) (*models.Session, error) {
|
|
|
|
if hash := session.GetHash(); hash != "" {
|
|
|
|
session, ok := s.hashes[hash]
|
|
|
|
if ok {
|
|
|
|
return session, &ErrSessionAlreadyPresent{hash}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
session.Quizzes = make(map[string]*models.Quiz, 0)
|
|
|
|
session.Answers = make(map[string]*models.Answer, 0)
|
|
|
|
|
|
|
|
for _, exam := range session.Exams {
|
|
|
|
for _, quiz := range exam.Quizzes {
|
|
|
|
session.Quizzes[quiz.ID] = quiz
|
|
|
|
|
|
|
|
for _, answer := range quiz.Answers {
|
|
|
|
session.Answers[answer.ID] = answer
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
sess, err := s.Store.Create(session)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return sess, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *SessionStore) Update(session *models.Session, id string) (*models.Session, error) {
|
|
|
|
_, err := s.Read(id)
|
|
|
|
if err != nil {
|
|
|
|
return session, err
|
|
|
|
}
|
|
|
|
|
|
|
|
session.Quizzes = make(map[string]*models.Quiz, 0)
|
|
|
|
session.Answers = make(map[string]*models.Answer, 0)
|
|
|
|
|
|
|
|
for _, exam := range session.Exams {
|
|
|
|
for _, quiz := range exam.Quizzes {
|
|
|
|
session.Quizzes[quiz.ID] = quiz
|
|
|
|
|
|
|
|
for _, answer := range quiz.Answers {
|
|
|
|
session.Answers[answer.ID] = answer
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
sess, err := s.Store.Update(session, id)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return sess, nil
|
|
|
|
}
|