35 lines
2.8 KiB
TypeScript
35 lines
2.8 KiB
TypeScript
import { and, eq } from "drizzle-orm";
|
|
import { getDb } from "../../../db";
|
|
import { mockExams, studyDays } from "../../../db/schema";
|
|
|
|
const user = (r: Request) => r.headers.get("oai-authenticated-user-id");
|
|
const validDate = (s?: string) => /^2026-(09|10|11|12)-\d{2}$/.test(s || "");
|
|
|
|
export async function GET(r: Request) {
|
|
const id = user(r); if (!id) return Response.json({ error: "请登录后再使用学习中心。" }, { status: 401 });
|
|
try { const db = getDb(); return Response.json({ studyDays: await db.select().from(studyDays).where(eq(studyDays.userId, id)), mockExams: await db.select().from(mockExams).where(eq(mockExams.userId, id)) }); }
|
|
catch { return Response.json({ error: "暂时无法读取学习数据。" }, { status: 500 }); }
|
|
}
|
|
|
|
export async function PUT(r: Request) {
|
|
const id = user(r); if (!id) return Response.json({ error: "请登录后再保存。" }, { status: 401 });
|
|
const b = await r.json() as { type?: string; date?: string; durations?: Record<string, number>; weeklyReview?: string; nextFocus?: string; listening?: string; reading?: string; writing?: string; translation?: string; note?: string };
|
|
if (!validDate(b.date)) return Response.json({ error: "日期格式不正确。" }, { status: 400 });
|
|
try {
|
|
const db = getDb(), now = new Date().toISOString();
|
|
if (b.type === "day") {
|
|
const durations = Object.fromEntries(Object.entries(b.durations || {}).map(([k, v]) => [k, Math.max(0, Math.min(600, Number(v) || 0))]));
|
|
const values = { userId: id, planDate: b.date!, durations: JSON.stringify(durations), weeklyReview: (b.weeklyReview || "").slice(0, 1500), nextFocus: (b.nextFocus || "").slice(0, 400), updatedAt: now };
|
|
await db.insert(studyDays).values(values).onConflictDoUpdate({ target: [studyDays.userId, studyDays.planDate], set: values });
|
|
return Response.json({ studyDay: (await db.select().from(studyDays).where(and(eq(studyDays.userId, id), eq(studyDays.planDate, b.date!))))[0] });
|
|
}
|
|
if (b.type === "mock") {
|
|
const clean = (v?: string) => String(v || "").replace(/[^\d.]/g, "").slice(0, 6);
|
|
const values = { userId: id, examDate: b.date!, listening: clean(b.listening), reading: clean(b.reading), writing: clean(b.writing), translation: clean(b.translation), note: (b.note || "").slice(0, 1000), updatedAt: now };
|
|
await db.insert(mockExams).values(values).onConflictDoUpdate({ target: [mockExams.userId, mockExams.examDate], set: values });
|
|
return Response.json({ mockExam: (await db.select().from(mockExams).where(and(eq(mockExams.userId, id), eq(mockExams.examDate, b.date!))))[0] });
|
|
}
|
|
return Response.json({ error: "请求类型不正确。" }, { status: 400 });
|
|
} catch { return Response.json({ error: "暂时无法保存,请稍后重试。" }, { status: 500 }); }
|
|
}
|