Skip to content

Commit 80cd92f

Browse files
committed
feat: implement /v1/translate and /v1/explain routes and preserve legacy / endpoint
1 parent 40a5602 commit 80cd92f

File tree

1 file changed

+66
-20
lines changed

1 file changed

+66
-20
lines changed

backend/src/index.ts

Lines changed: 66 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -16,39 +16,85 @@ export default {
1616
return new Response(null, { headers: corsHeaders });
1717
}
1818

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-
}
19+
const url = new URL(request.url);
20+
const path = url.pathname;
21+
const genAI = new GoogleGenerativeAI(env.GEMINI_API_KEY);
22+
const model = genAI.getGenerativeModel({ model: 'gemini-2.0-flash' });
2823

29-
const genAI = new GoogleGenerativeAI(env.GEMINI_API_KEY);
24+
try {
25+
//Function for handling the translation
26+
const handleTranslate = async () => {
27+
const { code, targetLanguage } = await request.json<{ code: string; targetLanguage: string }>();
3028

31-
const model = genAI.getGenerativeModel({ model: 'gemini-2.0-flash' });
29+
if (!code || !targetLanguage) {
30+
return new Response(JSON.stringify({ error: "Missing 'code' or 'targetLanguage' in request body." }), {
31+
status: 400,
32+
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
33+
});
34+
}
3235

33-
const prompt = `Translate the following code snippet to ${targetLanguage}.
36+
const prompt = `Translate the following code snippet to ${targetLanguage}.
3437
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.**
38+
**IMPORTANT: Preserve all original comments and their exact placement in the translated code. Do not add extra spaces in between.**
3639
Only provide the raw, translated code itself.
3740
3841
Original Code:
3942
${code}`;
4043

41-
const result = await model.generateContent(prompt);
42-
const geminiResponse = result.response;
43-
const translatedCode = geminiResponse.text();
44+
const result = await model.generateContent(prompt);
45+
const translatedCode = result.response.text();
46+
47+
return new Response(JSON.stringify({ translation: translatedCode }), {
48+
status: 200,
49+
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
50+
});
51+
};
52+
//Function for handling the explanation
53+
const handleExplain = async () => {
54+
const { code } = await request.json<{ code: string }>();
55+
56+
if (!code) {
57+
return new Response(JSON.stringify({ error: "Missing 'code' in request body." }), {
58+
status: 400,
59+
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
60+
});
61+
}
4462

45-
return new Response(JSON.stringify({ translation: translatedCode }), {
46-
status: 200,
63+
const prompt = `Explain the following code snippet in detail:
64+
1. Provide a clear breakdown of what each part (functions, variables, logic blocks) does.
65+
2. If applicable, describe the overall purpose or intent of the code.
66+
3. Offer a step-by-step explanation of how the code executes.
67+
4. If the code is executable, show a sample input and the corresponding output.
68+
5. Keep the explanation beginner-friendly but technically accurate.
69+
70+
Code:
71+
${code}`;
72+
73+
const result = await model.generateContent(prompt);
74+
const explanation = result.response.text();
75+
76+
return new Response(JSON.stringify({ explanation }), {
77+
status: 200,
78+
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
79+
});
80+
};
81+
if (path === '/') {
82+
return handleTranslate();
83+
}
84+
if (path === '/v1/translate') {
85+
return handleTranslate();
86+
}
87+
if (path === '/v1/explain') {
88+
return handleExplain();
89+
}
90+
// Fallback for unknown paths
91+
return new Response(JSON.stringify({ error: 'Route not found.' }), {
92+
status: 404,
4793
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
4894
});
4995
} catch (error) {
50-
console.error('Error during translation:', error);
51-
return new Response(JSON.stringify({ error: 'An error occurred while translating the code.' }), {
96+
console.error('Error during request:', error);
97+
return new Response(JSON.stringify({ error: 'An internal error occurred.' }), {
5298
status: 500,
5399
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
54100
});

0 commit comments

Comments
 (0)