UNPKG

nexus-react-core

Version:

A comprehensive React toolkit with services, hooks, and Redux store management

315 lines 12 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.fetchFacebookDirectData = fetchFacebookDirectData; exports.fetchTwitterDirectData = fetchTwitterDirectData; exports.fetchTestData = fetchTestData; exports.fetchRealisticTestData = fetchRealisticTestData; const config_1 = require("../config"); /** * Fetch Facebook direct page data from the backend * @param pageId - Optional Facebook page ID (uses backend default if not provided) * @param token - Authentication token (optional, will try to get from localStorage) * @returns Promise with Facebook page data */ async function fetchFacebookDirectData(pageId, token) { try { const config = (0, config_1.getConfig)(); const authToken = token || (typeof window !== "undefined" ? localStorage.getItem('token') || sessionStorage.getItem('token') : null); // Build query parameters const params = new URLSearchParams(); if (pageId) { params.append('pageId', pageId); } const url = `${config.apiBaseUrl}/social-engagement/direct/facebook${params.toString() ? `?${params.toString()}` : ''}`; console.log('🔗 Calling Facebook API:', url); console.log('🔑 Auth token available:', !!authToken); const headers = { 'Content-Type': 'application/json', }; // Only add Authorization header if token is available if (authToken) { headers['Authorization'] = `Bearer ${authToken}`; } const response = await fetch(url, { method: 'GET', headers, }); console.log('📡 Response status:', response.status); if (!response.ok) { // If first attempt fails with auth, try without auth (in case endpoint doesn't require it) if (authToken && response.status === 401) { console.log('🔄 Retrying without authentication...'); const retryResponse = await fetch(url, { method: 'GET', headers: { 'Content-Type': 'application/json', }, }); if (retryResponse.ok) { console.log('✅ Retry successful!'); const data = await retryResponse.json(); return data; } } const errorData = await response.json().catch(() => ({})); throw new Error(errorData.message || `HTTP error! status: ${response.status}`); } console.log('✅ API call successful!'); const data = await response.json(); return data; } catch (error) { console.error('❌ Facebook Direct Data Fetch Error:', error); // Return a structured error response return { success: false, data: { summary: { totalPosts: 0, totalImpressions: 0, totalReach: 0, totalEngagement: 0, totalLikes: 0, totalComments: 0, totalShares: 0, totalSaved: 0, avgEngagementRate: 0, }, recentPosts: [], demographics: { locations: [], genders: [], ages: [], }, trends: [], isConnected: false, source: 'error', permissions: { pageAccess: false, insights: false, posts: false, }, }, message: error instanceof Error ? error.message : 'Failed to fetch Facebook data', error: error, }; } } /** * Fetch Twitter user analytics data from the backend * @param username - Optional Twitter username (uses backend default if not provided) * @param token - Authentication token (optional, will try to get from localStorage) * @returns Promise with Twitter user data */ async function fetchTwitterDirectData(username, token) { try { const config = (0, config_1.getConfig)(); const authToken = token || (typeof window !== "undefined" ? localStorage.getItem('token') || sessionStorage.getItem('token') : null); // Build query parameters const params = new URLSearchParams(); if (username) { params.append('username', username); } const url = `${config.apiBaseUrl}/twitter/analytics/user${params.toString() ? `?${params.toString()}` : ''}`; console.log('🔗 Calling Twitter API:', url); console.log('🔑 Auth token available:', !!authToken); const headers = { 'Content-Type': 'application/json', }; // Only add Authorization header if token is available if (authToken) { headers['Authorization'] = `Bearer ${authToken}`; } const response = await fetch(url, { method: 'GET', headers, }); console.log('📡 Response status:', response.status); if (!response.ok) { // If first attempt fails with auth, try without auth (in case endpoint doesn't require it) if (authToken && response.status === 401) { console.log('🔄 Retrying without authentication...'); const retryResponse = await fetch(url, { method: 'GET', headers: { 'Content-Type': 'application/json', }, }); if (retryResponse.ok) { console.log('✅ Retry successful!'); const data = await retryResponse.json(); return data; } } const errorData = await response.json().catch(() => ({})); throw new Error(errorData.message || `HTTP error! status: ${response.status}`); } console.log('✅ API call successful!'); const data = await response.json(); return data; } catch (error) { console.error('❌ Twitter Direct Data Fetch Error:', error); // Return a structured error response return { success: false, data: { summary: { totalTweets: 0, totalLikes: 0, totalRetweets: 0, totalReplies: 0, totalImpressions: 0, followers: 0, following: 0, avgEngagementRate: 0, }, user: { id: 'error_user_id', username: 'error_user', name: 'Error User', description: 'Error loading user data', profileImageUrl: null, verified: false, createdAt: new Date().toISOString(), followers: 0, following: 0, tweetCount: 0, }, recentTweets: [], isConnected: false, source: 'error', note: 'Failed to load Twitter data', }, message: error instanceof Error ? error.message : 'Failed to fetch Twitter data', error: error, }; } } /** * Fetch test data for development/testing purposes * @param token - Authentication token (optional, will try to get from localStorage) * @returns Promise with test data */ async function fetchTestData(token) { try { const config = (0, config_1.getConfig)(); const authToken = token || (typeof window !== "undefined" ? localStorage.getItem('token') || sessionStorage.getItem('token') : null); const headers = { 'Content-Type': 'application/json', }; // Only add Authorization header if token is available if (authToken) { headers['Authorization'] = `Bearer ${authToken}`; } const response = await fetch(`${config.apiBaseUrl}/social-engagement/test-data`, { method: 'GET', headers, }); if (!response.ok) { const errorData = await response.json().catch(() => ({})); throw new Error(errorData.message || `HTTP error! status: ${response.status}`); } const data = await response.json(); return data; } catch (error) { console.error('Test Data Fetch Error:', error); return { success: false, data: { summary: { totalPosts: 0, totalImpressions: 0, totalReach: 0, totalEngagement: 0, totalLikes: 0, totalComments: 0, totalShares: 0, totalSaved: 0, avgEngagementRate: 0, }, recentPosts: [], demographics: { locations: [], genders: [], ages: [], }, trends: [], isConnected: false, source: 'error', permissions: { pageAccess: false, insights: false, posts: false, }, }, message: error instanceof Error ? error.message : 'Failed to fetch test data', error: error, }; } } /** * Fetch realistic test data with proper formatting * @param token - Authentication token (optional, will try to get from localStorage) * @returns Promise with realistic test data */ async function fetchRealisticTestData(token) { try { const config = (0, config_1.getConfig)(); const authToken = token || (typeof window !== "undefined" ? localStorage.getItem('token') || sessionStorage.getItem('token') : null); const headers = { 'Content-Type': 'application/json', }; // Only add Authorization header if token is available if (authToken) { headers['Authorization'] = `Bearer ${authToken}`; } const response = await fetch(`${config.apiBaseUrl}/social-engagement/test-data/realistic`, { method: 'GET', headers, }); if (!response.ok) { const errorData = await response.json().catch(() => ({})); throw new Error(errorData.message || `HTTP error! status: ${response.status}`); } const data = await response.json(); return data; } catch (error) { console.error('Realistic Test Data Fetch Error:', error); return { success: false, data: { summary: { totalPosts: 0, totalImpressions: 0, totalReach: 0, totalEngagement: 0, totalLikes: 0, totalComments: 0, totalShares: 0, totalSaved: 0, avgEngagementRate: 0, }, recentPosts: [], demographics: { locations: [], genders: [], ages: [], }, trends: [], isConnected: false, source: 'error', permissions: { pageAccess: false, insights: false, posts: false, }, }, message: error instanceof Error ? error.message : 'Failed to fetch realistic test data', error: error, }; } } //# sourceMappingURL=socialEngagementService.js.map