oef/orm/question.go

102 lines
2 KiB
Go
Raw Normal View History

2019-11-04 15:00:46 +01:00
package orm
import (
"net/http"
2019-11-13 12:15:29 +01:00
"git.andreafazzi.eu/andrea/oef/renderer"
"github.com/jinzhu/gorm"
2019-11-04 15:00:46 +01:00
)
type Question struct {
gorm.Model
Text string
Answers []*Answer
2019-11-04 15:00:46 +01:00
}
func (q *Question) GetID() uint { return q.ID }
func (q *Question) String() string {
return q.Text
}
func (q *Question) Create(args map[string]string, r *http.Request) (interface{}, error) {
2019-11-13 12:15:29 +01:00
if r.Method == "GET" {
2019-11-13 13:57:41 +01:00
return nil, nil
2019-11-13 12:15:29 +01:00
} else {
question := new(Question)
err := renderer.Decode(question, r)
if err != nil {
return nil, err
}
question, err = CreateQuestion(question)
if err != nil {
return nil, err
}
return question, nil
}
2019-11-04 15:00:46 +01:00
}
func (q *Question) Read(args map[string]string, r *http.Request) (interface{}, error) {
var question Question
id := args["id"]
if err := DB().Preload("Answers").Where("id = ?", id).Find(&question).Error; err != nil {
return nil, err
}
return &question, nil
2019-11-04 15:00:46 +01:00
}
func (q *Question) ReadAll(args map[string]string, r *http.Request) (interface{}, error) {
var questions []*Question
if err := DB().Order("created_at").Find(&questions).Error; err != nil {
return nil, err
}
return questions, nil
}
func (q *Question) Update(args map[string]string, r *http.Request) (interface{}, error) {
if r.Method == "GET" {
return q.Read(args, r)
} else {
question, err := q.Read(args, nil)
if err != nil {
return nil, err
}
err = renderer.Decode(question, r)
if err != nil {
return nil, err
}
_, err = SaveQuestion(question)
if err != nil {
return nil, err
}
question, err = q.Read(args, nil)
if err != nil {
return nil, err
}
return question.(*Question), nil
}
2019-11-04 15:00:46 +01:00
}
func (q *Question) Delete(args map[string]string, r *http.Request) (interface{}, error) {
return nil, nil
}
2019-11-13 12:15:29 +01:00
func CreateQuestion(question *Question) (*Question, error) {
if err := DB().Create(question).Error; err != nil {
return nil, err
}
return question, nil
}
func SaveQuestion(question interface{}) (interface{}, error) {
if err := DB().Omit("Answers").Save(question).Error; err != nil {
return nil, err
}
return question, nil
}