Seo/Template-01/server.ts
2026-05-05 11:30:03 -03:00

93 lines
2.8 KiB
TypeScript

import express from 'express';
import { createServer as createViteServer } from 'vite';
import { GoogleGenerativeAI } from "@google/generative-ai";
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 genAI: GoogleGenerativeAI | null = null;
const getAIModel = () => {
const apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
throw new Error("GEMINI_API_KEY environment variable is required");
}
if (!genAI) {
genAI = new GoogleGenerativeAI(apiKey);
}
return genAI.getGenerativeModel({ model: "gemini-1.5-flash-8b" });
};
// Translation API
app.post('/api/translate', async (req, res) => {
const { text, targetLang, context, isObject } = req.body;
try {
const model = getAIModel();
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 result = await model.generateContent(prompt);
const response = await result.response;
let resultText = response.text().replace(/```json/g, '').replace(/```/g, '').trim();
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();