47 lines
1.5 KiB
TypeScript
47 lines
1.5 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { createWord, listWords, type Grade } from "@/lib/db";
|
|
|
|
export const runtime = "nodejs";
|
|
export const dynamic = "force-dynamic";
|
|
|
|
export async function GET(request: NextRequest) {
|
|
const searchParams = request.nextUrl.searchParams;
|
|
const grade = searchParams.get("grade") ?? undefined;
|
|
const classTypeId = Number(searchParams.get("classTypeId"));
|
|
const enabledOnly = searchParams.get("enabledOnly") === "true";
|
|
|
|
const words = listWords({
|
|
grade,
|
|
classTypeId: Number.isFinite(classTypeId) && classTypeId > 0 ? classTypeId : undefined,
|
|
enabledOnly,
|
|
});
|
|
|
|
return NextResponse.json({ words });
|
|
}
|
|
|
|
export async function POST(request: NextRequest) {
|
|
try {
|
|
const body = await request.json();
|
|
const word = createWord({
|
|
grade: body.grade as Grade,
|
|
classTypeId: Number(body.classTypeId),
|
|
english: String(body.english ?? ""),
|
|
chinese: String(body.chinese ?? ""),
|
|
image: String(body.image ?? ""),
|
|
audio: String(body.audio ?? ""),
|
|
enabled: Boolean(body.enabled),
|
|
});
|
|
|
|
return NextResponse.json({ word }, { status: 201 });
|
|
} catch (error) {
|
|
return NextResponse.json({ message: getErrorMessage(error) }, { status: 400 });
|
|
}
|
|
}
|
|
|
|
function getErrorMessage(error: unknown) {
|
|
const message = error instanceof Error ? error.message : "操作失败";
|
|
if (message.includes("UNIQUE")) return "相同年级、班级类型和英语题库已存在";
|
|
if (message.includes("FOREIGN KEY")) return "班级类型不存在";
|
|
return message;
|
|
}
|