// نام فایل: dictionary-gemini-proxy.js (یا هر نامی که برای ورکر خود انتخاب می‌کنید) export default { async fetch(request, env, ctx) { const GEMINI_API_URL_BASE = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent"; // یا هر مدلی که استفاده می‌کنید // کلید API جمنای خود را باید به عنوان یک "Secret" یا "Environment Variable" // در تنظیمات این Worker در داشبورد Cloudflare با نام GEMINI_API_KEY ذخیره کنید. const API_KEY = env.GEMINI_API_KEY; if (!API_KEY) { return new Response(JSON.stringify({ error: { message: "API key is not configured in the proxy worker." } }), { status: 500, headers: { 'Content-Type': 'application/json' } }); } const targetUrl = `\{GEMINI\_API\_URL\_BASE\}?key\={API_KEY}`; if (request.method === "POST") { let requestBody; try { requestBody = await request.json(); } catch (e) { return new Response(JSON.stringify({ error: { message: "Invalid JSON body in request to proxy." } }), { status: 400, headers: { 'Content-Type': 'application/json' } }); } const geminiRequest = new Request(targetUrl, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(requestBody), }); try { const geminiResponse = await fetch(geminiRequest); // Ensure Cloudflare doesn't alter the response from Gemini by creating a new Response object // This helps with issues like "corrupted content" or "incorrect header" const responseBody = await geminiResponse.arrayBuffer(); const responseHeaders = new Headers(geminiResponse.headers); // Crucially, set the content type correctly for the client responseHeaders.set('Content-Type', 'application/json'); return new Response(responseBody, { status: geminiResponse.status, statusText: geminiResponse.statusText, headers: responseHeaders }); } catch (error) { console.error("Error fetching from Gemini API via proxy:", error); return new Response(JSON.stringify({ error: { message: "Error connecting to the Gemini API through proxy." } }), { status: 502, // Bad Gateway headers: { 'Content-Type': 'application/json' } }); } } return new Response(JSON.stringify({ error: { message: "This proxy only accepts POST requests." } }), { status: 405, // Method Not Allowed headers: { 'Content-Type': 'application/json' } }); }, };