从零搭建基于 AI 问答平台(13) 添加检查答案功能

效果

实现步骤如下:

添加 CheckAnswer API

添加 src/app/api/checkAnswer/route.ts:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
export async function POST(req: Request, res: Response) {
...
const body = await req.json();
const { questionId, userInput } = checkAnswerSchema.parse(body);
const question = await prisma.question.findUnique({
where: { id: questionId },
});

if (question.questionType === "mcq") {
const isCorrect =
question.answer.toLowerCase().trim() === userInput.toLowerCase().trim();
await prisma.question.update({
where: { id: questionId },
data: { isCorrect },
});
return NextResponse.json({
isCorrect,
});
}
...

添加 end game API

添加 ``:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const game = await prisma.game.findUnique({
where: {
id: gameId,
},
});
...
await prisma.game.update({
where: {
id: gameId,
},
data: {
timeEnded: new Date(),
},
});

和 mcq 页面整合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

const { mutate: checkAnswer, isPending: isChecking } = useMutation({
mutationFn: async () => {
const payload: z.infer<typeof checkAnswerSchema> = {
questionId: currentQuestion.id,
userInput: options[selectedChoice],
};
const response = await axios.post(`/api/checkAnswer`, payload);
return response.data;
},
});

const { mutate: endGame } = useMutation({
mutationFn: async () => {
const payload: z.infer<typeof endGameSchema> = {
gameId: game.id,
};
const response = await axios.post(`/api/endGame`, payload);
return response.data;
},
});

const handleNext = React.useCallback(() => {
checkAnswer(undefined, {
onSuccess: ({ isCorrect }) => {
if (isCorrect) {
setStats((stats) => ({
...stats,
correct_answers: stats.correct_answers + 1,
}));
toast("Correct",{
description: "You got it right!",
});
} else {
setStats((stats) => ({
...stats,
wrong_answers: stats.wrong_answers + 1,
}));
toast("Incorrect",{
description: "You got it wrong!",
});
}

if (questionIndex === game.questions.length - 1) {
endGame();
setHasEnded(true);
return;
}

setQuestionIndex((questionIndex) => questionIndex + 1);
setSelectedChoice(0); // 重置选中的选项
},
});
}, [checkAnswer, questionIndex, game.questions.length, toast, endGame]);

...
<Button
variant="default"
className="mt-2"
size="lg"
disabled={isChecking || hasEnded}
onClick={() => {
handleNext();
}}
>
{isChecking && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
Next <ChevronRight className="w-4 h-4 ml-2" />
</Button>

如果感兴趣本项目,请访问项目目录: 从零搭建基于 AI 问答平台 - 目录


作者:Bearalise
出处:从零搭建基于 AI 问答平台(13) 添加检查答案功能
版权:本文版权归作者所有
转载:欢迎转载,但未经作者同意,必须保留此段声明,必须在文章中给出原文链接。

请我喝杯咖啡吧~

支付宝
微信