82 lines
1.6 KiB
Go
82 lines
1.6 KiB
Go
package store
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"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
|
|
}
|