export async function onRequestGet(context) { const token = context.env.INSTAGRAM_ACCESS_TOKEN; if (!token) { return new Response( JSON.stringify({ error: "Instagram token not configured" }), { status: 500, headers: { "Content-Type": "application/json" }, } ); } try { const profileUrl = "https://graph.instagram.com/me" + "?fields=id,username,profile_picture_url" + `&access_token=${encodeURIComponent(token)}`; const mediaFields = [ "id", "caption", "media_type", "media_url", "thumbnail_url", "permalink", "timestamp", ].join(","); const mediaUrl = "https://graph.instagram.com/me/media" + `?fields=${encodeURIComponent(mediaFields)}` + "&limit=12" + `&access_token=${encodeURIComponent(token)}`; const [profileResponse, mediaResponse] = await Promise.all([ fetch(profileUrl), fetch(mediaUrl), ]); const profile = await profileResponse.json(); const media = await mediaResponse.json(); if (!profileResponse.ok) { return new Response( JSON.stringify({ error: "Instagram profile request failed", details: profile, }), { status: profileResponse.status, headers: { "Content-Type": "application/json" }, } ); } if (!mediaResponse.ok) { return new Response( JSON.stringify({ error: "Instagram media request failed", details: media, }), { status: mediaResponse.status, headers: { "Content-Type": "application/json" }, } ); } return new Response( JSON.stringify({ profile: { id: profile.id, username: profile.username, profile_picture_url: profile.profile_picture_url, }, media: media.data || [], }), { status: 200, headers: { "Content-Type": "application/json", "Cache-Control": "public, max-age=300", }, } ); } catch (error) { return new Response( JSON.stringify({ error: "Instagram request failed", }), { status: 500, headers: { "Content-Type": "application/json" }, } ); } }