Skip to content

Commit 9a76586

Browse files
feat: implement /v1/translate and /v1/explain routes and preserve legacy / endpoint #26 from hemanth5055/feat/add-v1-api-routes
2 parents 728f685 + 531e36b commit 9a76586

File tree

1 file changed

+74
-30
lines changed

1 file changed

+74
-30
lines changed

backend/src/index.ts

Lines changed: 74 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -4,51 +4,95 @@ export interface Env {
44
GEMINI_API_KEY: string;
55
}
66

7+
const corsHeaders = {
8+
'Access-Control-Allow-Origin': '*',
9+
'Access-Control-Allow-Methods': 'POST, OPTIONS',
10+
'Access-Control-Allow-Headers': 'Content-Type',
11+
};
12+
13+
async function handleTranslate(request: Request, model: ReturnType<GoogleGenerativeAI['getGenerativeModel']>) {
14+
const { code, targetLanguage } = await request.json<{ code: string; targetLanguage: string }>();
15+
16+
if (!code || !targetLanguage) {
17+
return new Response(JSON.stringify({ error: "Missing 'code' or 'targetLanguage' in request body." }), {
18+
status: 400,
19+
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
20+
});
21+
}
22+
23+
const prompt = `Translate the following code snippet to ${targetLanguage}.
24+
Do not add any explanation, commentary, or markdown formatting like \`\`\` around the code.
25+
**IMPORTANT: Preserve all original comments and their exact placement in the translated code. Do not add extra spaces in between.**
26+
Only provide the raw, translated code itself.
27+
28+
Original Code:
29+
${code}`;
30+
31+
const result = await model.generateContent(prompt);
32+
const translatedCode = result.response.text();
33+
34+
return new Response(JSON.stringify({ translation: translatedCode }), {
35+
status: 200,
36+
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
37+
});
38+
}
39+
40+
async function handleExplain(request: Request, model: ReturnType<GoogleGenerativeAI['getGenerativeModel']>) {
41+
const { code } = await request.json<{ code: string }>();
42+
43+
if (!code) {
44+
return new Response(JSON.stringify({ error: "Missing 'code' in request body." }), {
45+
status: 400,
46+
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
47+
});
48+
}
49+
50+
const prompt = `Explain the following code snippet in detail:
51+
1. Provide a clear breakdown of what each part (functions, variables, logic blocks) does.
52+
2. If applicable, describe the overall purpose or intent of the code.
53+
3. Offer a step-by-step explanation of how the code executes.
54+
4. If the code is executable, show a sample input and the corresponding output.
55+
5. Keep the explanation beginner-friendly but technically accurate.
56+
57+
Code:
58+
${code}`;
59+
60+
const result = await model.generateContent(prompt);
61+
const explanation = result.response.text();
62+
63+
return new Response(JSON.stringify({ explanation }), {
64+
status: 200,
65+
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
66+
});
67+
}
68+
769
export default {
870
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-
1571
if (request.method === 'OPTIONS') {
1672
return new Response(null, { headers: corsHeaders });
1773
}
1874

1975
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-
76+
const url = new URL(request.url);
77+
const path = url.pathname;
2978
const genAI = new GoogleGenerativeAI(env.GEMINI_API_KEY);
30-
3179
const model = genAI.getGenerativeModel({ model: 'gemini-2.0-flash' });
3280

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}`;
81+
if (path === '/' || path === '/v1/translate') {
82+
return await handleTranslate(request, model);
83+
}
4084

41-
const result = await model.generateContent(prompt);
42-
const geminiResponse = result.response;
43-
const translatedCode = geminiResponse.text();
85+
if (path === '/v1/explain') {
86+
return await handleExplain(request, model);
87+
}
4488

45-
return new Response(JSON.stringify({ translation: translatedCode }), {
46-
status: 200,
89+
return new Response(JSON.stringify({ error: 'Route not found.' }), {
90+
status: 404,
4791
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
4892
});
4993
} catch (error) {
50-
console.error('Error during translation:', error);
51-
return new Response(JSON.stringify({ error: 'An error occurred while translating the code.' }), {
94+
console.error('Error during request:', error);
95+
return new Response(JSON.stringify({ error: 'An internal error occurred.' }), {
5296
status: 500,
5397
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
5498
});

0 commit comments

Comments
 (0)