Files
daily-question/backend/src/router/daily/index.ts
2025-11-24 18:58:32 +08:00

178 lines
4.4 KiB
TypeScript

import { generateId } from '../../module/utils.ts';
import { app } from '../../app.ts';
import { getDb } from '../../module/db.ts';
import { dailyQuestions } from '../../module/schema.ts';
import { eq, and, or, like } from 'drizzle-orm';
// 列出每日问题
app.route({
description: '列出每日问题',
path: 'daily',
key: 'list',
middleware: ['auth']
}).define(async (ctx) => {
const query = ctx.query;
const page = query.page ?? 1;
const pageSize = query.pageSize ?? 99999;
const db = getDb();
const search = query.search ?? '';
const id = query.id ?? '';
try {
const offset = (page - 1) * pageSize;
const allResults = await db.select().from(dailyQuestions).where(() => {
const conditions = [];
if (search) {
conditions.push(like(dailyQuestions.title, `%${search}%`));
}
if (id) {
conditions.push(eq(dailyQuestions.id, id));
}
// 如果需要 OR 逻辑(search 或 id 任一匹配)
return conditions.length > 0 ? or(...conditions) : undefined;
// 如果需要 AND 逻辑(search 和 id 都要匹配)
// return conditions.length > 0 ? and(...conditions) : undefined;
});
// Sort by createdAt in descending order (newest first)
const sortedResults = allResults.sort((a, b) =>
new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
);
const list = sortedResults.slice(offset, offset + pageSize);
const totalResult = await db.select().from(dailyQuestions);
const total = totalResult.length;
ctx.body = {
list,
pagination: {
page,
pageSize,
total,
},
};
} catch (error) {
console.error('获取问题列表失败:', error);
ctx.throw(500, '获取问题列表失败');
}
}).addTo(app);
// 更新每日问题
app.route({
description: '更新每日问题',
path: 'daily',
key: 'update',
middleware: ['auth']
}).define(async (ctx) => {
const query = ctx.query;
const id = query.id;
const db = getDb();
const body = query;
try {
if (!id) {
// 新增数据
const newQuestion = await db
.insert(dailyQuestions)
.values({
id: generateId(),
title: body.title,
description: body.description,
tags: JSON.stringify(body.tags || []),
date: body.date || new Date().toISOString().split('T')[0],
qid: body.qid,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
})
.returning();
ctx.body = newQuestion[0];
} else {
// 更新数据
const updated = await db
.update(dailyQuestions)
.set({
title: body.title,
description: body.description,
tags: JSON.stringify(body.tags || []),
date: body.date,
qid: body.qid,
updatedAt: new Date().toISOString(),
})
.where(eq(dailyQuestions.id, id))
.returning();
if (updated.length === 0) {
ctx.throw(404, '数据未找到');
}
ctx.body = { success: true, data: updated[0] };
}
} catch (error) {
console.error('更新数据失败:', error);
ctx.throw(500, '更新数据失败');
}
}).addTo(app);
// 删除每日问题
app.route({
description: '删除每日问题',
path: 'daily',
key: 'delete',
middleware: ['auth']
}).define(async (ctx) => {
const query = ctx.query;
const id = query.id;
const db = getDb();
try {
if (!id) {
ctx.throw(400, '缺少ID参数');
}
const deleted = await db
.delete(dailyQuestions)
.where(eq(dailyQuestions.id, id))
.returning();
ctx.body = deleted;
} catch (error) {
console.error('删除数据失败:', error);
ctx.throw(500, '删除数据失败');
}
}).addTo(app);
// 获取每日问题详情
app.route({
description: '获取每日问题详情',
path: 'daily',
key: 'detail',
middleware: ['auth']
}).define(async (ctx) => {
const query = ctx.query;
const id = query.id;
const db = getDb();
try {
if (!id) {
ctx.throw(400, '缺少ID参数');
}
const result = await db
.select()
.from(dailyQuestions)
.where(eq(dailyQuestions.id, id));
if (result.length === 0) {
ctx.throw(404, '数据未找到');
}
ctx.body = result[0];
} catch (error) {
console.error('获取数据详情失败:', error);
ctx.throw(500, '获取数据详情失败');
}
}).addTo(app);