generated from template/router-template
113 lines
2.9 KiB
TypeScript
113 lines
2.9 KiB
TypeScript
import { generateId, getTodayDate } from '../module/utils.ts';
|
|
import { app } from '../app.ts';
|
|
import { getDb } from '../module/db.ts';
|
|
import { dailyQuestions, questionLibrary } from '../module/schema.ts';
|
|
import { eq } from 'drizzle-orm';
|
|
|
|
app.route({
|
|
path: 'daily',
|
|
key: 'random',
|
|
description: '随机获取一条未使用的问题'
|
|
}).define(async (ctx) => {
|
|
const force = ctx.query.force ?? false;
|
|
const db = getDb();
|
|
const day = getTodayDate();
|
|
if (force) {
|
|
const existingQuestion = await db
|
|
.select()
|
|
.from(dailyQuestions)
|
|
.where(eq(dailyQuestions.date, day))
|
|
.limit(1)
|
|
.get();
|
|
|
|
if (existingQuestion) {
|
|
// 删除dailyQuestions中的记录
|
|
await db
|
|
.delete(dailyQuestions)
|
|
.where(eq(dailyQuestions.id, existingQuestion.id));
|
|
console.log('已强制删除当天的问题记录', day);
|
|
}
|
|
}
|
|
|
|
try {
|
|
// 从questionLibrary中随机获取一条isUse为false的问题
|
|
const unusedQuestions = await db
|
|
.select()
|
|
.from(questionLibrary)
|
|
.where(eq(questionLibrary.isUse, false));
|
|
|
|
if (unusedQuestions.length === 0) {
|
|
ctx.throw(404, '没有未使用的问题');
|
|
return;
|
|
}
|
|
|
|
const randomIndex = Math.floor(Math.random() * unusedQuestions.length);
|
|
const selectedQuestion = unusedQuestions[randomIndex];
|
|
|
|
// 更新questionLibrary中的isUse和usedAt字段
|
|
await db
|
|
.update(questionLibrary)
|
|
.set({
|
|
isUse: true,
|
|
usedAt: day,
|
|
})
|
|
.where(eq(questionLibrary.id, selectedQuestion.id));
|
|
|
|
|
|
// 将选中的问题添加到dailyQuestions中
|
|
const insertedQuestions = await db
|
|
.insert(dailyQuestions)
|
|
.values({
|
|
id: generateId(),
|
|
qid: selectedQuestion.id,
|
|
title: selectedQuestion.title,
|
|
description: '',
|
|
tags: selectedQuestion.tags,
|
|
date: day,
|
|
createdAt: new Date().toISOString(),
|
|
updatedAt: new Date().toISOString(),
|
|
}).returning();
|
|
ctx.body = { question: insertedQuestions[0], day: day };
|
|
} catch (error) {
|
|
console.error('随机获取问题失败:', error);
|
|
ctx.throw(500, '随机获取问题失败');
|
|
}
|
|
}).addTo(app);
|
|
|
|
app.route({
|
|
description: '获取今天的问题',
|
|
path: 'daily',
|
|
key: 'today'
|
|
}).define(async (ctx) => {
|
|
const db = getDb();
|
|
const day = getTodayDate();
|
|
|
|
try {
|
|
const todayQuestion = await db
|
|
.select()
|
|
.from(dailyQuestions)
|
|
.where(eq(dailyQuestions.date, day))
|
|
.limit(1)
|
|
.get();
|
|
|
|
if (!todayQuestion) {
|
|
const res = await ctx.call({
|
|
path: 'daily',
|
|
key: 'random',
|
|
});
|
|
if (res.code === 200) {
|
|
ctx.body = res.body;
|
|
return;
|
|
}
|
|
ctx.throw(500, '获取今天的问题失败');
|
|
}
|
|
|
|
ctx.body = {
|
|
question: todayQuestion,
|
|
day: day,
|
|
};
|
|
} catch (error) {
|
|
console.error('获取今天的问题失败:', error);
|
|
ctx.throw(500, '获取今天的问题失败');
|
|
}
|
|
}).addTo(app); |