From 80cd92f4ab45be982a8b60a4712fca6d18db2a13 Mon Sep 17 00:00:00 2001 From: hemanth5055 Date: Mon, 4 Aug 2025 20:50:48 +0530 Subject: [PATCH 1/2] feat: implement /v1/translate and /v1/explain routes and preserve legacy / endpoint --- backend/src/index.ts | 86 +++++++++++++++++++++++++++++++++----------- 1 file changed, 66 insertions(+), 20 deletions(-) diff --git a/backend/src/index.ts b/backend/src/index.ts index 73194ad..8f5d503 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -16,39 +16,85 @@ export default { return new Response(null, { headers: corsHeaders }); } - try { - const { code, targetLanguage } = await request.json<{ code: string; targetLanguage: string }>(); - - if (!code || !targetLanguage) { - return new Response(JSON.stringify({ error: "Missing 'code' or 'targetLanguage' in request body." }), { - status: 400, - headers: { ...corsHeaders, 'Content-Type': 'application/json' }, - }); - } + const url = new URL(request.url); + const path = url.pathname; + const genAI = new GoogleGenerativeAI(env.GEMINI_API_KEY); + const model = genAI.getGenerativeModel({ model: 'gemini-2.0-flash' }); - const genAI = new GoogleGenerativeAI(env.GEMINI_API_KEY); + try { + //Function for handling the translation + const handleTranslate = async () => { + const { code, targetLanguage } = await request.json<{ code: string; targetLanguage: string }>(); - const model = genAI.getGenerativeModel({ model: 'gemini-2.0-flash' }); + if (!code || !targetLanguage) { + return new Response(JSON.stringify({ error: "Missing 'code' or 'targetLanguage' in request body." }), { + status: 400, + headers: { ...corsHeaders, 'Content-Type': 'application/json' }, + }); + } - const prompt = `Translate the following code snippet to ${targetLanguage}. + const prompt = `Translate the following code snippet to ${targetLanguage}. Do not add any explanation, commentary, or markdown formatting like \`\`\` around the code. -**IMPORTANT: Preserve all original comments and their exact placement in the translated code. do not add extra spaces in between.** +**IMPORTANT: Preserve all original comments and their exact placement in the translated code. Do not add extra spaces in between.** Only provide the raw, translated code itself. Original Code: ${code}`; - const result = await model.generateContent(prompt); - const geminiResponse = result.response; - const translatedCode = geminiResponse.text(); + const result = await model.generateContent(prompt); + const translatedCode = result.response.text(); + + return new Response(JSON.stringify({ translation: translatedCode }), { + status: 200, + headers: { ...corsHeaders, 'Content-Type': 'application/json' }, + }); + }; + //Function for handling the explanation + const handleExplain = async () => { + const { code } = await request.json<{ code: string }>(); + + if (!code) { + return new Response(JSON.stringify({ error: "Missing 'code' in request body." }), { + status: 400, + headers: { ...corsHeaders, 'Content-Type': 'application/json' }, + }); + } - return new Response(JSON.stringify({ translation: translatedCode }), { - status: 200, + const prompt = `Explain the following code snippet in detail: +1. Provide a clear breakdown of what each part (functions, variables, logic blocks) does. +2. If applicable, describe the overall purpose or intent of the code. +3. Offer a step-by-step explanation of how the code executes. +4. If the code is executable, show a sample input and the corresponding output. +5. Keep the explanation beginner-friendly but technically accurate. + +Code: +${code}`; + + const result = await model.generateContent(prompt); + const explanation = result.response.text(); + + return new Response(JSON.stringify({ explanation }), { + status: 200, + headers: { ...corsHeaders, 'Content-Type': 'application/json' }, + }); + }; + if (path === '/') { + return handleTranslate(); + } + if (path === '/v1/translate') { + return handleTranslate(); + } + if (path === '/v1/explain') { + return handleExplain(); + } + // Fallback for unknown paths + return new Response(JSON.stringify({ error: 'Route not found.' }), { + status: 404, headers: { ...corsHeaders, 'Content-Type': 'application/json' }, }); } catch (error) { - console.error('Error during translation:', error); - return new Response(JSON.stringify({ error: 'An error occurred while translating the code.' }), { + console.error('Error during request:', error); + return new Response(JSON.stringify({ error: 'An internal error occurred.' }), { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' }, }); From 531e36ba011ec5cf51fceb1d4d373c85af0631a0 Mon Sep 17 00:00:00 2001 From: hemanth5055 Date: Tue, 5 Aug 2025 12:57:43 +0530 Subject: [PATCH 2/2] Minor fixes based on review comments --- backend/src/index.ts | 120 +++++++++++++++++++++---------------------- 1 file changed, 59 insertions(+), 61 deletions(-) diff --git a/backend/src/index.ts b/backend/src/index.ts index 8f5d503..7dcaf21 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -4,36 +4,23 @@ export interface Env { GEMINI_API_KEY: string; } -export default { - async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { - const corsHeaders = { - 'Access-Control-Allow-Origin': '*', - 'Access-Control-Allow-Methods': 'POST, OPTIONS', - 'Access-Control-Allow-Headers': 'Content-Type', - }; +const corsHeaders = { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'POST, OPTIONS', + 'Access-Control-Allow-Headers': 'Content-Type', +}; - if (request.method === 'OPTIONS') { - return new Response(null, { headers: corsHeaders }); - } +async function handleTranslate(request: Request, model: ReturnType) { + const { code, targetLanguage } = await request.json<{ code: string; targetLanguage: string }>(); - const url = new URL(request.url); - const path = url.pathname; - const genAI = new GoogleGenerativeAI(env.GEMINI_API_KEY); - const model = genAI.getGenerativeModel({ model: 'gemini-2.0-flash' }); + if (!code || !targetLanguage) { + return new Response(JSON.stringify({ error: "Missing 'code' or 'targetLanguage' in request body." }), { + status: 400, + headers: { ...corsHeaders, 'Content-Type': 'application/json' }, + }); + } - try { - //Function for handling the translation - const handleTranslate = async () => { - const { code, targetLanguage } = await request.json<{ code: string; targetLanguage: string }>(); - - if (!code || !targetLanguage) { - return new Response(JSON.stringify({ error: "Missing 'code' or 'targetLanguage' in request body." }), { - status: 400, - headers: { ...corsHeaders, 'Content-Type': 'application/json' }, - }); - } - - const prompt = `Translate the following code snippet to ${targetLanguage}. + const prompt = `Translate the following code snippet to ${targetLanguage}. Do not add any explanation, commentary, or markdown formatting like \`\`\` around the code. **IMPORTANT: Preserve all original comments and their exact placement in the translated code. Do not add extra spaces in between.** Only provide the raw, translated code itself. @@ -41,26 +28,26 @@ Only provide the raw, translated code itself. Original Code: ${code}`; - const result = await model.generateContent(prompt); - const translatedCode = result.response.text(); - - return new Response(JSON.stringify({ translation: translatedCode }), { - status: 200, - headers: { ...corsHeaders, 'Content-Type': 'application/json' }, - }); - }; - //Function for handling the explanation - const handleExplain = async () => { - const { code } = await request.json<{ code: string }>(); - - if (!code) { - return new Response(JSON.stringify({ error: "Missing 'code' in request body." }), { - status: 400, - headers: { ...corsHeaders, 'Content-Type': 'application/json' }, - }); - } - - const prompt = `Explain the following code snippet in detail: + const result = await model.generateContent(prompt); + const translatedCode = result.response.text(); + + return new Response(JSON.stringify({ translation: translatedCode }), { + status: 200, + headers: { ...corsHeaders, 'Content-Type': 'application/json' }, + }); +} + +async function handleExplain(request: Request, model: ReturnType) { + const { code } = await request.json<{ code: string }>(); + + if (!code) { + return new Response(JSON.stringify({ error: "Missing 'code' in request body." }), { + status: 400, + headers: { ...corsHeaders, 'Content-Type': 'application/json' }, + }); + } + + const prompt = `Explain the following code snippet in detail: 1. Provide a clear breakdown of what each part (functions, variables, logic blocks) does. 2. If applicable, describe the overall purpose or intent of the code. 3. Offer a step-by-step explanation of how the code executes. @@ -70,24 +57,35 @@ ${code}`; Code: ${code}`; - const result = await model.generateContent(prompt); - const explanation = result.response.text(); + const result = await model.generateContent(prompt); + const explanation = result.response.text(); - return new Response(JSON.stringify({ explanation }), { - status: 200, - headers: { ...corsHeaders, 'Content-Type': 'application/json' }, - }); - }; - if (path === '/') { - return handleTranslate(); - } - if (path === '/v1/translate') { - return handleTranslate(); + return new Response(JSON.stringify({ explanation }), { + status: 200, + headers: { ...corsHeaders, 'Content-Type': 'application/json' }, + }); +} + +export default { + async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { + if (request.method === 'OPTIONS') { + return new Response(null, { headers: corsHeaders }); + } + + try { + const url = new URL(request.url); + const path = url.pathname; + const genAI = new GoogleGenerativeAI(env.GEMINI_API_KEY); + const model = genAI.getGenerativeModel({ model: 'gemini-2.0-flash' }); + + if (path === '/' || path === '/v1/translate') { + return await handleTranslate(request, model); } + if (path === '/v1/explain') { - return handleExplain(); + return await handleExplain(request, model); } - // Fallback for unknown paths + return new Response(JSON.stringify({ error: 'Route not found.' }), { status: 404, headers: { ...corsHeaders, 'Content-Type': 'application/json' },