39 lines
1.3 KiB
TypeScript
39 lines
1.3 KiB
TypeScript
|
|
import { NextApiHandler } from "next";
|
||
|
|
import NextCors from "nextjs-cors";
|
||
|
|
import { replicateTranslate } from "@utils/replicate-translate";
|
||
|
|
import { readSettings } from "@utils/settings-store";
|
||
|
|
|
||
|
|
type Data = { translation: string } | { error: string };
|
||
|
|
|
||
|
|
const handler: NextApiHandler<Data> = async (req, res) => {
|
||
|
|
await NextCors(req, res, { methods: ["POST"], origin: "*" });
|
||
|
|
|
||
|
|
if (req.method !== "POST") {
|
||
|
|
res.setHeader("Allow", ["POST"]);
|
||
|
|
return res.status(405).json({ error: "Method Not Allowed" });
|
||
|
|
}
|
||
|
|
|
||
|
|
const settings = readSettings();
|
||
|
|
if (!settings.replicateEnabled) {
|
||
|
|
return res.status(503).json({ error: "Replicate translation is not enabled" });
|
||
|
|
}
|
||
|
|
|
||
|
|
const { text, targetLanguage } = req.body ?? {};
|
||
|
|
if (!text || typeof text !== "string") {
|
||
|
|
return res.status(400).json({ error: "text is required" });
|
||
|
|
}
|
||
|
|
if (!targetLanguage || typeof targetLanguage !== "string") {
|
||
|
|
return res.status(400).json({ error: "targetLanguage is required" });
|
||
|
|
}
|
||
|
|
|
||
|
|
try {
|
||
|
|
const translation = await replicateTranslate(text, targetLanguage);
|
||
|
|
return res.status(200).json({ translation });
|
||
|
|
} catch (err) {
|
||
|
|
const msg = err instanceof Error ? err.message : "Translation failed";
|
||
|
|
return res.status(500).json({ error: msg });
|
||
|
|
}
|
||
|
|
};
|
||
|
|
|
||
|
|
export default handler;
|