Files
kozmos-web/app/actions/instagram.ts
T

69 lines
2.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use server";
export async function getInstagramPosts() {
try {
const response = await fetch('https://instagram120.p.rapidapi.com/api/instagram/posts?v=1', {
method: 'POST',
headers: {
'x-rapidapi-key': process.env.RAPIDAPI_KEY || '762dc41c1dmshc120ecf29aa240ap11dc66jsn87f410b870f5',
'x-rapidapi-host': 'instagram120.p.rapidapi.com',
'Content-Type': 'application/json'
},
body: JSON.stringify({ username: 'kozmosbeach', maxId: '' }),
// CRITICAL ADIM: Veriyi 24 saat boyunca önbellekte tut (Saniye cinsinden: 24 * 60 * 60)
next: { revalidate: 86400 }
});
if (!response.ok) {
throw new Error("Instagram API request failed");
}
const data = await response.json();
// The RapidAPI endpoint usually returns an array of posts or { data: { items: [...] } }
// Based on standard Instagram120 response, it returns { result: { edges: [{node: {}}] } }
let posts = [];
if (data && data.result && data.result.edges && Array.isArray(data.result.edges)) {
posts = data.result.edges.map((edge: any) => edge.node);
} else if (data && Array.isArray(data)) {
posts = data;
} else if (data && data.data && Array.isArray(data.data)) {
posts = data.data;
} else if (data && data.items && Array.isArray(data.items)) {
posts = data.items;
}
// Map to a cleaner format and take first 4
const formattedPosts = posts.slice(0, 4).map((post: any) => {
// Instagram API has multiple variants for post schema
const id = post.id || post.pk;
const code = post.code;
// Try to find the highest res image
let imageUrl = "";
if (post.image_versions2 && post.image_versions2.candidates) {
imageUrl = post.image_versions2.candidates[0].url;
} else if (post.carousel_media && post.carousel_media.length > 0) {
imageUrl = post.carousel_media[0].image_versions2.candidates[0].url;
} else if (post.display_url) {
imageUrl = post.display_url;
}
const caption = post.caption?.text || post.caption || "";
const url = code ? `https://instagram.com/p/${code}` : `https://instagram.com/kozmosbeach`;
return {
id,
imageUrl,
url,
caption
};
});
return { success: true, data: formattedPosts };
} catch (error) {
console.error("Error fetching Instagram posts:", error);
return { success: false, error: "Instagram gönderileri alınamadı." };
}
}