|
| 1 | +import { GoogleGenerativeAI } from '@google/generative-ai'; |
| 2 | + |
| 3 | +export interface Env { |
| 4 | + GEMINI_API_KEY: string; |
| 5 | +} |
| 6 | + |
| 7 | +export default { |
| 8 | + async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> { |
| 9 | + const corsHeaders = { |
| 10 | + 'Access-Control-Allow-Origin': '*', |
| 11 | + 'Access-Control-Allow-Methods': 'POST, OPTIONS', |
| 12 | + 'Access-Control-Allow-Headers': 'Content-Type', |
| 13 | + }; |
| 14 | + |
| 15 | + if (request.method === 'OPTIONS') { |
| 16 | + return new Response(null, { headers: corsHeaders }); |
| 17 | + } |
| 18 | + |
| 19 | + try { |
| 20 | + const { code, targetLanguage } = await request.json<{ code: string; targetLanguage: string }>(); |
| 21 | + |
| 22 | + if (!code || !targetLanguage) { |
| 23 | + return new Response(JSON.stringify({ error: "Missing 'code' or 'targetLanguage' in request body." }), { |
| 24 | + status: 400, |
| 25 | + headers: { ...corsHeaders, 'Content-Type': 'application/json' }, |
| 26 | + }); |
| 27 | + } |
| 28 | + |
| 29 | + const genAI = new GoogleGenerativeAI(env.GEMINI_API_KEY); |
| 30 | + |
| 31 | + const model = genAI.getGenerativeModel({ model: 'gemini-2.0-flash' }); |
| 32 | + |
| 33 | + const prompt = `Translate the following code snippet to ${targetLanguage}. |
| 34 | +Do not add any explanation, commentary, or markdown formatting like \`\`\` around the code. |
| 35 | +**IMPORTANT: Preserve all original comments and their exact placement in the translated code. do not add extra spaces in between.** |
| 36 | +Only provide the raw, translated code itself. |
| 37 | +
|
| 38 | +Original Code: |
| 39 | +${code}`; |
| 40 | + |
| 41 | + const result = await model.generateContent(prompt); |
| 42 | + const geminiResponse = result.response; |
| 43 | + const translatedCode = geminiResponse.text(); |
| 44 | + |
| 45 | + return new Response(JSON.stringify({ translation: translatedCode }), { |
| 46 | + status: 200, |
| 47 | + headers: { ...corsHeaders, 'Content-Type': 'application/json' }, |
| 48 | + }); |
| 49 | + } catch (error) { |
| 50 | + console.error('Error during translation:', error); |
| 51 | + return new Response(JSON.stringify({ error: 'An error occurred while translating the code.' }), { |
| 52 | + status: 500, |
| 53 | + headers: { ...corsHeaders, 'Content-Type': 'application/json' }, |
| 54 | + }); |
| 55 | + } |
| 56 | + }, |
| 57 | +}; |
0 commit comments