oef/orm/answer.go

137 lines
2.9 KiB
Go
Raw Normal View History

package orm
import (
"net/http"
"git.andreafazzi.eu/andrea/oef/renderer"
"github.com/jinzhu/gorm"
)
type Answer struct {
gorm.Model
Text string
Correct bool
Question *Question
QuestionID uint `schema:"question_id"`
AllQuestions []*Question `gorm:"-"`
Selected map[uint]string `gorm:"-"`
}
func (a *Answer) GetID() uint { return a.ID }
func (a *Answer) String() string {
return a.Text
}
func (a *Answer) Create(args map[string]string, w http.ResponseWriter, r *http.Request) (interface{}, error) {
if r.Method == "GET" {
answer := new(Answer)
if err := DB().Find(&answer.AllQuestions).Error; err != nil {
return nil, err
}
return answer, nil
} else {
answer := new(Answer)
err := renderer.Decode(answer, r)
if err != nil {
return nil, err
}
answer, err = CreateAnswer(answer)
if err != nil {
return nil, err
}
return answer, nil
}
}
func (a *Answer) Read(args map[string]string, w http.ResponseWriter, r *http.Request) (interface{}, error) {
var answer Answer
id := args["id"]
if err := DB().Preload("Question").First(&answer, id).Error; err != nil {
return nil, err
}
return &answer, nil
}
func (a *Answer) ReadAll(args map[string]string, w http.ResponseWriter, r *http.Request) (interface{}, error) {
2019-11-13 13:57:41 +01:00
var answers []*Answer
2019-11-14 12:55:22 +01:00
if err := DB().Preload("Question").Order("created_at").Find(&answers).Error; err != nil {
return nil, err
}
2019-11-13 13:57:41 +01:00
return answers, nil
}
func (a *Answer) Update(args map[string]string, w http.ResponseWriter, r *http.Request) (interface{}, error) {
if r.Method == "GET" {
result, err := a.Read(args, w, r)
if err != nil {
return nil, err
}
answer := result.(*Answer)
if err := DB().Find(&answer.AllQuestions).Error; err != nil {
return nil, err
}
answer.Selected = make(map[uint]string)
answer.Selected[answer.QuestionID] = "selected"
return answer, nil
} else {
answer, err := a.Read(args, w, r)
if err != nil {
return nil, err
}
2019-11-14 12:55:22 +01:00
// FIXME: Should not be hard set.
answer.(*Answer).Correct = false
err = renderer.Decode(answer, r)
if err != nil {
return nil, err
}
_, err = SaveAnswer(answer)
if err != nil {
return nil, err
}
answer, err = a.Read(args, w, r)
if err != nil {
return nil, err
}
return answer.(*Answer), nil
}
}
func (model *Answer) Delete(args map[string]string, w http.ResponseWriter, r *http.Request) (interface{}, error) {
answer, err := model.Read(args, w, r)
if err != nil {
return nil, err
}
if err := DB().Unscoped().Delete(answer.(*Answer)).Error; err != nil {
return nil, err
}
return answer.(*Answer), nil
}
func CreateAnswer(answer *Answer) (*Answer, error) {
if err := DB().Create(answer).Error; err != nil {
return nil, err
}
return answer, nil
}
func SaveAnswer(answer interface{}) (interface{}, error) {
if err := DB().Omit("Answers").Save(answer).Error; err != nil {
return nil, err
}
return answer, nil
}