feat: initial commit
This commit is contained in:
@ -2,25 +2,90 @@ package setup
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"forge.cadoles.com/wpetit/kouiz/internal/config"
|
||||
"forge.cadoles.com/wpetit/kouiz/internal/http/handler/webui/quiz"
|
||||
"forge.cadoles.com/wpetit/kouiz/internal/store"
|
||||
"forge.cadoles.com/wpetit/kouiz/misc/quiz/openquizzdb"
|
||||
"github.com/glebarez/sqlite"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/datatypes"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func NewQuizHandlerFromConfig(ctx context.Context, conf *config.Config) (*quiz.Handler, error) {
|
||||
db, err := gorm.Open(sqlite.Open(string(conf.Store.DSN)), &gorm.Config{})
|
||||
db, err := gorm.Open(sqlite.Open(string(conf.Store.DSN)), &gorm.Config{
|
||||
NowFunc: func() time.Time {
|
||||
return time.Now().UTC()
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatalf("[FATAL] %+v", errors.Wrap(err, "could not open store"))
|
||||
return nil, errors.WithStack(err)
|
||||
}
|
||||
|
||||
if conf.Store.Debug {
|
||||
db = db.Debug()
|
||||
}
|
||||
|
||||
return quiz.NewHandler(store.New(db)), nil
|
||||
store := store.New(db)
|
||||
|
||||
if err := loadEmbeddedQuizz(ctx, store); err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
}
|
||||
|
||||
return quiz.NewHandler(store, conf.Quiz.PlayInterval), nil
|
||||
}
|
||||
|
||||
func loadEmbeddedQuizz(ctx context.Context, st *store.Store) error {
|
||||
quizz, err := openquizzdb.LoadAll()
|
||||
if err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
for _, q := range quizz {
|
||||
c := q.Categories["fr"]
|
||||
|
||||
category := &store.QuizCategory{
|
||||
Name: c.Name,
|
||||
Theme: c.Label,
|
||||
Description: c.Slogan,
|
||||
}
|
||||
|
||||
err := st.UpsertQuizCategory(ctx, category)
|
||||
if err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
quiz := q.Quizz["fr"]
|
||||
levels := [][]openquizzdb.Entry{
|
||||
quiz.Beginner,
|
||||
quiz.Intermediate,
|
||||
quiz.Expert,
|
||||
}
|
||||
|
||||
for i, l := range levels {
|
||||
for _, e := range l {
|
||||
entry := &store.QuizEntry{
|
||||
CategoryID: category.ID,
|
||||
Question: e.Question,
|
||||
Level: uint(i),
|
||||
Provider: "openquizzdb",
|
||||
ProviderID: fmt.Sprintf("%d-%d-%d", category.ID, i, e.ID),
|
||||
Propositions: datatypes.NewJSONSlice(e.Propositions),
|
||||
Answer: e.Answer,
|
||||
Anecdote: e.Anecdote,
|
||||
}
|
||||
|
||||
err := st.UpsertQuizEntry(ctx, entry)
|
||||
if err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
Reference in New Issue
Block a user