Seo/Template-04/server.ts

98 lines
2.7 KiB
TypeScript
Raw Normal View History

2026-05-05 14:34:21 +00:00
import express from 'express';
import { createServer as createViteServer } from 'vite';
import { GoogleGenAI } from "@google/genai";
import path from 'path';
import cors from 'cors';
async function startServer() {
const app = express();
const PORT = 3000;
app.use(express.json());
app.use(cors());
// Lazy Gemini Setup
let ai: GoogleGenAI | null = null;
const getAI = () => {
const apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
throw new Error("GEMINI_API_KEY environment variable is required");
}
if (!ai) {
ai = new GoogleGenAI({ apiKey });
}
return ai;
};
// Translation API
app.post('/api/translate', async (req, res) => {
const { text, targetLang, context, isObject } = req.body;
try {
const client = getAI();
let prompt = "";
if (isObject) {
prompt = `Translate the following JSON object values to ${targetLang}.
Keep the keys exactly the same.
Preserve markdown formatting in values.
Return ONLY the translated JSON object.
Object:
${JSON.stringify(text)}`;
} else {
prompt = `Translate the following ${context || 'text'} to ${targetLang}.
Preserve all markdown formatting, technical terms, and HTML structures if present.
Do not add any commentary or prefix. Return only the translated string.
Content:
${text}`;
}
const response = await client.models.generateContent({
model: "gemini-3-flash-preview",
contents: prompt,
config: isObject ? { responseMimeType: "application/json" } : undefined
});
let resultText = response.text || '';
if (isObject) {
try {
res.json({ translatedText: JSON.parse(resultText) });
} catch (e) {
console.error("Parse Error:", resultText);
res.json({ translatedText: text }); // Fallback to original if parse fails
}
} else {
res.json({ translatedText: resultText });
}
} catch (error) {
console.error("Translation Error:", error);
res.status(500).json({ error: error instanceof Error ? error.message : "Failed to translate" });
}
});
// Vite Integration
if (process.env.NODE_ENV !== "production") {
const vite = await createViteServer({
server: { middlewareMode: true },
appType: "spa",
});
app.use(vite.middlewares);
} else {
const distPath = path.join(process.cwd(), 'dist');
app.use(express.static(distPath));
app.get('*', (req, res) => {
res.sendFile(path.join(distPath, 'index.html'));
});
}
app.listen(PORT, "0.0.0.0", () => {
console.log(`Server running at http://0.0.0.0:${PORT}`);
});
}
startServer();