Skip to content

Commit b9050cc

Browse files
committed
feat: find random question
1 parent cf1417d commit b9050cc

File tree

2 files changed

+48
-4
lines changed

2 files changed

+48
-4
lines changed

apps/question-service/handlers/findmatchingquestion.go

Lines changed: 48 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,59 @@ package handlers
33
import (
44
"context"
55
"log"
6+
"math/rand"
67
pb "proto/questionmatching"
8+
"question-service/models"
9+
10+
"cloud.google.com/go/firestore"
711
)
812

913
func (s *GrpcServer) FindMatchingQuestion(ctx context.Context, req *pb.MatchQuestionRequest) (*pb.QuestionFound, error) {
1014
log.Printf("Received matching question request: %v", req)
15+
16+
var question *models.Question
17+
18+
// Match by both topic and difficulty
19+
20+
// Match by just topic
21+
22+
// Match by difficulty
23+
24+
// No matches, so return random question
25+
if question == nil {
26+
randomQuestion, err := retrieveRandomQuestion(s.Client, ctx)
27+
if err != nil {
28+
return nil, err
29+
}
30+
question = randomQuestion
31+
}
32+
1133
return &pb.QuestionFound{
12-
QuestionId: 1,
13-
QuestionName: "abc",
14-
QuestionDifficulty: "Easy",
15-
QuestionTopics: []string{"Algorithms", "Arrays"},
34+
QuestionId: question.ID,
35+
QuestionName: question.Title,
36+
QuestionDifficulty: question.Complexity.String(),
37+
QuestionTopics: question.Categories,
1638
}, nil
1739
}
40+
41+
func retrieveRandomQuestion(client *firestore.Client, ctx context.Context) (*models.Question, error) {
42+
// Count documents
43+
docs, err := client.Collection("questions").Documents(ctx).GetAll()
44+
if err != nil || len(docs) == 0 {
45+
log.Fatalf("No documents found: %v", err)
46+
}
47+
48+
// Generate a random offset
49+
randomOffset := rand.Intn(len(docs))
50+
51+
// Retrieve the document at the random offset
52+
doc := docs[randomOffset]
53+
var question models.Question
54+
if err := doc.DataTo(&question); err != nil {
55+
return nil, err
56+
57+
}
58+
question.DocRefID = doc.Ref.ID
59+
60+
return &question, nil
61+
}

0 commit comments

Comments
 (0)