hackathon/db/quest.go

96 lines
2.2 KiB
Go

package db
import (
"context"
"fmt"
"github.com/hhhapz/codequest/models"
"github.com/hhhapz/codequest/question"
)
func (db *DB) Questions(ctx context.Context, u *models.User) ([]*question.Data, error) {
parts, err := models.AllQuestionPartsData(ctx, db.DB, u.ID)
if err != nil {
return nil, err
}
var data []*question.Data
for _, q := range question.Questions {
var p1, p2 question.PartData
for _, p := range parts {
if p.QuestionID == q.ID {
p1, p2 = question.PartData{
Completed: p.P1Awarded.Valid,
PointsWorth: int(p.P1Awarded.Int64),
}, question.PartData{
Completed: p.P2Awarded.Valid,
PointsWorth: int(p.P2Awarded.Int64),
}
break
}
}
data = append(data, &question.Data{
Question: q,
UserID: u.ID,
Name: q.Name,
Part1: p1,
Part2: p2,
})
}
return data, nil
}
func (db *DB) Question(ctx context.Context, u *models.User, id string) (*question.Data, error) {
var q *question.Question
for _, qq := range question.Questions {
if qq.ID == id {
q = qq
break
}
}
if q == nil {
return nil, models.NewUserError("question with the id %q not found", id)
}
partData, err := models.QuestionPartsData(ctx, db.DB, q.ID, u.ID)
if err != nil {
return nil, fmt.Errorf("could not retrieve question data: %w", err)
}
return &question.Data{
Question: q,
UserID: u.ID,
Name: q.Name,
Text: q.Text,
Level: q.Level,
Part1: question.PartData{
Completed: partData.P1Awarded != 0,
PointsWorth: partData.P1Awarded,
Solution: partData.P1Answer,
},
Part2: question.PartData{
Completed: partData.P2Awarded != 0,
PointsWorth: partData.P2Awarded,
Solution: partData.P2Answer,
},
}, nil
}
func (db *DB) Submissions(ctx context.Context, u *models.User, questionID string, part question.Part) (bool, int, error) {
s, err := models.QuestionSubmissions(ctx, db.DB, u.ID, questionID, int(part))
if err != nil {
return false, 0, err
}
return s.Correct, s.ByUser, nil
}
func (db *DB) AddSubmission(ctx context.Context, submission *models.QuestionAttempt) error {
return submission.Insert(ctx, db.DB)
}
func (db *DB) Leaderboard(ctx context.Context) ([]*models.LeaderboardEntry, error) {
return models.Leaderboard(ctx, db.DB)
}