sync: Extract function that import flags from importer

This commit is contained in:
nemunaire 2019-07-05 22:28:56 +02:00
commit 4039a394b5
8 changed files with 438 additions and 294 deletions

View file

@ -8,22 +8,22 @@ import (
// MCQ represents a flag's challenge, in the form of checkbox.
type MCQ struct {
Id int64 `json:"id"`
Id int64 `json:"id"`
// IdExercice is the identifier of the underlying challenge
IdExercice int64 `json:"idExercice"`
IdExercice int64 `json:"idExercice"`
// Title is the label of the question
Title string `json:"title"`
Title string `json:"title"`
// Entries stores the set of proposed answers
Entries []MCQ_entry `json:"entries"`
Entries []MCQ_entry `json:"entries"`
}
// MCQ_entry represents a proposed response for a given MCQ.
type MCQ_entry struct {
Id int64 `json:"id"`
Id int64 `json:"id"`
// Label is the text displayed to players as proposed answer
Label string `json:"label"`
Label string `json:"label"`
// Response stores if expected checked state.
Response bool `json:"response"`
Response bool `json:"response"`
}
// GetMCQ returns the MCQs coming with the challenge.
@ -97,14 +97,31 @@ func GetMCQbyChoice(cid int64) (m MCQ, c MCQ_entry, err error) {
return
}
// AddMCQ creates and fills a new struct MCQ and registers it into the database.
func (e Exercice) AddMCQ(title string) (MCQ, error) {
if res, err := DBExec("INSERT INTO exercice_mcq (id_exercice, title) VALUES (?, ?)", e.Id, title); err != nil {
return MCQ{}, err
// GetId returns the MCQ identifier.
func (m MCQ) GetId() int64 {
return m.Id
}
// Create registers a MCQ into the database and recursively add its entries.
func (m MCQ) Create(e Exercice) (Flag, error) {
if res, err := DBExec("INSERT INTO exercice_mcq (id_exercice, title) VALUES (?, ?)", e.Id, m.Title); err != nil {
return m, err
} else if qid, err := res.LastInsertId(); err != nil {
return MCQ{}, err
return m, err
} else {
return MCQ{qid, e.Id, title, []MCQ_entry{}}, nil
m.Id = qid
m.IdExercice = e.Id
// Add entries
for k, entry := range m.Entries {
if entry, err = m.AddEntry(entry); err != nil {
return m, err
} else {
m.Entries[k] = entry
}
}
return m, nil
}
}
@ -135,13 +152,14 @@ func (m MCQ) Delete() (int64, error) {
}
// AddEntry creates and fills a new struct MCQ_entry and registers it into the database.
func (m MCQ) AddEntry(label string, response bool) (MCQ_entry, error) {
if res, err := DBExec("INSERT INTO mcq_entries (id_mcq, label, response) VALUES (?, ?, ?)", m.Id, label, response); err != nil {
return MCQ_entry{}, err
func (m MCQ) AddEntry(e MCQ_entry) (MCQ_entry, error) {
if res, err := DBExec("INSERT INTO mcq_entries (id_mcq, label, response) VALUES (?, ?, ?)", m.Id, e.Label, e.Response); err != nil {
return e, err
} else if nid, err := res.LastInsertId(); err != nil {
return MCQ_entry{}, err
return e, err
} else {
return MCQ_entry{nid, label, response}, nil
e.Id = nid
return e, nil
}
}