probo/session/session.go

75 lines
1.5 KiB
Go
Raw Normal View History

2023-12-11 09:32:50 +01:00
package session
import (
"bytes"
"encoding/json"
"io"
"net/http"
"git.andreafazzi.eu/andrea/probo/models"
"git.andreafazzi.eu/andrea/probo/store"
)
type Session struct {
Name string
ParticipantStore *store.ParticipantStore
QuizStore *store.QuizStore
ParticipantFilter map[string]string
QuizFilter map[string]string
ServerURL string
Token int
examStore *store.ExamStore
}
func NewSession(url string, name string, pStore *store.ParticipantStore, qStore *store.QuizStore, pFilter map[string]string, qFilter map[string]string) (*Session, error) {
session := new(Session)
session.ServerURL = url
session.examStore = store.NewStore[*models.Exam]()
for _, p := range pStore.ReadAll() {
_, err := session.examStore.Create(&models.Exam{
Name: name,
Participant: p,
Quizzes: qStore.ReadAll(),
})
if err != nil {
return nil, err
}
}
return session, nil
}
func (s *Session) GetExams() []*models.Exam {
return s.examStore.ReadAll()
}
func (s *Session) Push() (string, error) {
payload, err := json.Marshal(s.examStore.ReadAll())
if err != nil {
return "", err
}
response, err := http.Post(s.ServerURL, "application/json", bytes.NewReader(payload))
if err != nil {
return "", err
}
responseBody, err := io.ReadAll(response.Body)
if err != nil {
return "", err
}
result := map[string]string{}
err = json.Unmarshal(responseBody, &result)
if err != nil {
return "", err
}
return result["id"], nil
}