96 lines
2.6 KiB
Go
96 lines
2.6 KiB
Go
package api
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"errors"
|
|
"log"
|
|
|
|
codequestpb "github.com/hhhapz/codequest/api/v1"
|
|
"github.com/hhhapz/codequest/models"
|
|
"google.golang.org/grpc/codes"
|
|
"google.golang.org/grpc/status"
|
|
"google.golang.org/protobuf/types/known/emptypb"
|
|
)
|
|
|
|
type QuestService struct {
|
|
codequestpb.UnimplementedQuestServiceServer
|
|
|
|
questStore QuestStore
|
|
userStore UserStore
|
|
}
|
|
|
|
func (qs *QuestService) Questions(ctx context.Context, req *emptypb.Empty) (*codequestpb.QuestionsResponse, error) {
|
|
u := UserCtx(ctx)
|
|
|
|
questions, err := qs.questStore.Questions(ctx, u)
|
|
if err != nil {
|
|
if errors.As(err, &models.UserError{}) {
|
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
|
}
|
|
return nil, status.Errorf(codes.Internal, "could not get questions: internal error")
|
|
}
|
|
|
|
res := new(codequestpb.QuestionsResponse)
|
|
|
|
for _, q := range questions {
|
|
res.Questions = append(res.Questions, &codequestpb.Question{
|
|
ID: q.QuestionID,
|
|
Title: q.Name,
|
|
Part1: &codequestpb.PartData{
|
|
Completed: q.Part1.Completed,
|
|
PointsWorth: int32(q.Part1.PointsWorth),
|
|
},
|
|
Part2: &codequestpb.PartData{
|
|
Completed: q.Part2.Completed,
|
|
PointsWorth: int32(q.Part2.PointsWorth),
|
|
},
|
|
})
|
|
}
|
|
|
|
return res, nil
|
|
}
|
|
|
|
func (qs *QuestService) QuestionByID(ctx context.Context, req *codequestpb.QuestionByIDRequest) (*codequestpb.Question, error) {
|
|
u := UserCtx(ctx)
|
|
|
|
question, err := qs.questStore.Question(ctx, u, req.ID)
|
|
if err != nil {
|
|
if errors.As(err, &models.UserError{}) {
|
|
return nil, status.Error(codes.InvalidArgument, err.Error())
|
|
}
|
|
return nil, status.Errorf(codes.Internal, "could not get question: internal error")
|
|
}
|
|
|
|
content := new(bytes.Buffer)
|
|
err = question.Text.Execute(content, question)
|
|
if err != nil {
|
|
log.Printf("could gen write question %s template: %v", req.ID, err)
|
|
return nil, status.Errorf(codes.Internal, "could not get question: internal error")
|
|
}
|
|
|
|
q := &codequestpb.Question{
|
|
ID: question.QuestionID,
|
|
Title: question.Name,
|
|
Text: content.String(),
|
|
Part1: &codequestpb.PartData{
|
|
Completed: question.Part1.Completed,
|
|
PointsWorth: int32(question.Part1.PointsWorth),
|
|
},
|
|
Part2: &codequestpb.PartData{
|
|
Completed: question.Part2.Completed,
|
|
PointsWorth: int32(question.Part2.PointsWorth),
|
|
},
|
|
}
|
|
|
|
return q, nil
|
|
}
|
|
|
|
func (qs *QuestService) QuestionInput(ctx context.Context, req *codequestpb.QuestionInputRequest) (*codequestpb.QuestionInput, error) {
|
|
panic("not implemented") // TODO: Implement
|
|
}
|
|
|
|
func (qs *QuestService) Submit(ctx context.Context, req *codequestpb.SubmitRequest) (*codequestpb.SubmitResponse, error) {
|
|
panic("not implemented") // TODO: Implement
|
|
}
|