add two new models - Answer and Question

This commit is contained in:
Dawid Wysokiński 2021-02-27 09:11:15 +01:00
parent 888734b722
commit ef786b45c1
2 changed files with 81 additions and 0 deletions

49
internal/models/answer.go Normal file
View File

@ -0,0 +1,49 @@
package models
import (
"fmt"
"io"
"strconv"
"strings"
)
type Answer string
const (
AnswerA Answer = "a"
AnswerB Answer = "b"
AnswerC Answer = "c"
AnswerD Answer = "d"
)
func (role Answer) IsValid() bool {
switch role {
case AnswerA,
AnswerB,
AnswerC,
AnswerD:
return true
}
return false
}
func (answer Answer) String() string {
return string(answer)
}
func (answer *Answer) UnmarshalGQL(v interface{}) error {
str, ok := v.(string)
if !ok {
return fmt.Errorf("enums must be strings")
}
*answer = Answer(strings.ToLower(str))
if !answer.IsValid() {
return fmt.Errorf("%s is not a valid Answer", str)
}
return nil
}
func (answer Answer) MarshalGQL(w io.Writer) {
fmt.Fprint(w, strconv.Quote(answer.String()))
}

View File

@ -0,0 +1,32 @@
package models
import (
"context"
"time"
)
type Question struct {
ID int `json:"id" xml:"id" gqlgen:"id"`
From string `pg:",unique:group_1" json:"from" xml:"from" gqlgen:"from"`
Content string `pg:",unique:group_1,notnull" json:"content" xml:"content" gqlgen:"content"`
Explanation string `json:"explanation" xml:"explanation" gqlgen:"explanation"`
CorrectAnswer Answer `pg:",unique:group_1,notnull" json:"correctAnswer" xml:"correctAnswer" gqlgen:"correctAnswer"`
Image string `json:"image" xml:"image" gqlgen:"image"`
AnswerA Answer `json:"answerA" xml:"answerA" gqlgen:"answerA"`
AnswerAImage string `json:"answerAImage" xml:"answerAImage" gqlgen:"answerAImage"`
AnswerB Answer `json:"answerB" xml:"answerB" gqlgen:"answerB"`
AnswerBImage string `json:"answerBImage" xml:"answerBImage" gqlgen:"answerBImage"`
AnswerC Answer `json:"answerC" xml:"answerC" gqlgen:"answerC"`
AnswerCImage string `json:"answerCImage" xml:"answerCImage" gqlgen:"answerCImage"`
AnswerD Answer `json:"answerD" xml:"answerD" gqlgen:"answerD"`
AnswerDImage string `json:"answerDImage" xml:"answerDImage" gqlgen:"answerDImage"`
QualificationID int `pg:",unique:group_1,notnull" json:"qualificationID" xml:"qualificationID" gqlgen:"qualificationID"`
Qualification *Qualification `pg:"rel:has-one" json:"qualification" xml:"qualification" gqlgen:"qualification"`
CreatedAt time.Time `json:"createdAt,omitempty" pg:"default:now()" xml:"createdAt" gqlgen:"createdAt"`
}
func (q *Question) BeforeInsert(ctx context.Context) (context.Context, error) {
q.CreatedAt = time.Now()
return ctx, nil
}