Files
2026-04-18 23:52:15 +08:00

69 lines
2.0 KiB
TypeScript

import {NextRequest, NextResponse} from "next/server";
import {batchTranslateWithAI, translateWithAI} from "@/lib/ai-translate";
// 单个翻译
export async function GET(request: NextRequest) {
const {searchParams} = new URL(request.url);
const word = searchParams.get("word");
if (!word) {
return NextResponse.json({error: "缺少 word 参数"}, {status: 400});
}
try {
const translation = await translateWithAI(word);
if (!translation) {
return NextResponse.json({error: "翻译失败"}, {status: 500});
}
return NextResponse.json({
word,
english: translation,
});
} catch (error) {
console.error("AI translation error:", error);
return NextResponse.json(
{error: String(error)},
{status: 500}
);
}
}
// 批量翻译
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const {words} = body as { words: string[] };
if (!Array.isArray(words) || words.length === 0) {
return NextResponse.json({error: "缺少 words 参数(数组)"}, {status: 400});
}
// 检查 API Key
if (!process.env.AI_API_KEY) {
return NextResponse.json({error: "AI 配置未完成,请先在设置中配置 AI"}, {status: 500});
}
const results = await batchTranslateWithAI(words);
// 转换为响应格式
const translations: Record<string, string | null> = {};
for (const word of words) {
translations[word] = results.get(word) || null;
}
return NextResponse.json({
translations,
total: words.length,
success: results.size,
});
} catch (error) {
console.error("AI batch translation error:", error);
return NextResponse.json(
{error: String(error)},
{status: 500}
);
}
}