import fetch from 'node-fetch'; import { createClient } from '@supabase/supabase-js'; import * as dotenv from 'dotenv'; import * as path from 'path'; import * as fs from 'fs'; // Load environment variables const envLocalPath = path.resolve(process.cwd(), '../.env.local'); if (fs.existsSync(envLocalPath)) { console.log(`Loading environment from: ${envLocalPath}`); dotenv.config({ path: envLocalPath }); } else { console.log(`No .env.local file found at: ${envLocalPath}`); dotenv.config(); // Try loading from default .env } // Define types for the API response interface Category { id: number; name: string; slug: string; icon: string; description: string; tools_count: number; news_count: number; learning_count: number; posts_count: number; total_count: number; counts?: { tools: number; news: number; learning: number; posts: number; total: number; }; [key: string]: any; } async function testCategoriesApi() { console.log('Testing Categories API with count fields...'); // Initialize Supabase client for direct database verification const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL; const supabaseKey = process.env.SUPABASE_SERVICE_ROLE_KEY; if (!supabaseUrl || !supabaseKey) { console.error('Missing Supabase environment variables. Add NEXT_PUBLIC_SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY to .env.local'); process.exit(1); } const supabase = createClient(supabaseUrl, supabaseKey); // Adjust URL based on your local development setup const baseUrl = 'http://localhost:3000'; try { // Test 1: Basic categories request console.log('\n1. Testing basic categories request...'); const response = await fetch(`${baseUrl}/api/categories`); if (!response.ok) { throw new Error(`API request failed with status ${response.status}`); } const categories = await response.json() as Category[]; if (!Array.isArray(categories)) { throw new Error('Expected categories to be an array'); } console.log(`Received ${categories.length} categories`); // Check the first category for count fields if (categories.length > 0) { const firstCategory = categories[0]; console.log('\nFirst category sample:'); console.log(JSON.stringify(firstCategory, null, 2)); // Verify the count fields exist const requiredFields = ['tools_count', 'news_count', 'learning_count', 'posts_count', 'total_count']; const missingFields = requiredFields.filter(field => !(field in firstCategory)); if (missingFields.length > 0) { console.error(`❌ Missing required fields: ${missingFields.join(', ')}`); } else { console.log('✅ All required count fields are present'); } } else { console.log('No categories found to test'); } // Test 2: Categories with includeCount=true console.log('\n2. Testing categories with includeCount=true...'); const countResponse = await fetch(`${baseUrl}/api/categories?includeCount=true`); if (!countResponse.ok) { throw new Error(`API request failed with status ${countResponse.status}`); } const countCategories = await countResponse.json() as Category[]; if (countCategories.length > 0) { const category = countCategories[0]; console.log('First category with includeCount=true:'); console.log(JSON.stringify(category, null, 2)); // Check if both new top-level counts and nested counts exist const hasTopLevelCounts = 'tools_count' in category; const hasNestedCounts = category.counts && 'tools' in category.counts; if (hasTopLevelCounts && hasNestedCounts) { console.log('✅ Both top-level count fields and nested counts object exist'); } else if (!hasTopLevelCounts) { console.error('❌ Top-level count fields are missing'); } else if (!hasNestedCounts) { console.error('❌ Nested counts object is missing'); } } // Test 3: Verify count accuracy for a specific category console.log('\n3. Testing count accuracy for categories with data...'); // Get a few categories to test (including some that may have data) const categoriesToTest = [ categories.find(cat => cat.name === 'Code Assistant'), categories.find(cat => cat.name === 'LLMs'), categories.find(cat => cat.name === 'Vector Database'), categories.find(cat => cat.name === 'AI Training'), categories.find(cat => cat.name === 'Image Generation') ].filter(Boolean) as Category[]; if (categoriesToTest.length === 0) { console.log('Could not find any suitable categories for testing count accuracy'); return; } console.log(`Found ${categoriesToTest.length} categories to test`); // Test each category for (const targetCategory of categoriesToTest) { console.log(`\nTesting category: ${targetCategory.name} (${targetCategory.id})`); // Count tools let toolsQuery = supabase .from('tools') .select('*', { count: 'exact', head: true }) .eq('category_id', targetCategory.id) .eq('published', true); const { count: directToolsCount, error: toolsError } = await toolsQuery; if (toolsError) { console.error('Error counting tools directly:', toolsError); } // Also count tools from the junction table // First, get published tool IDs const { data: publishedTools } = await supabase .from('tools') .select('id') .eq('published', true); const publishedToolIds = publishedTools ? publishedTools.map(item => item.id) : []; // Then count tools from junction table where tool_id is in published tool IDs let toolsJunctionCount = 0; if (publishedToolIds.length > 0) { const { count: junctionCount, error: junctionError } = await supabase .from('tools_categories') .select('*', { count: 'exact', head: true }) .eq('category_id', targetCategory.id) .in('tool_id', publishedToolIds); if (junctionError) { console.error('Error counting tools from junction table:', junctionError); } else { toolsJunctionCount = junctionCount || 0; } } // Use the larger count to avoid undercounting const actualToolsCount = Math.max(directToolsCount || 0, toolsJunctionCount); // Count news - using let to declare mutable variable let newsQuery = supabase .from('news') .select('*', { count: 'exact', head: true }) .eq('category_id', targetCategory.id) .eq('published', true); const { count: directNewsCount, error: newsError } = await newsQuery; if (newsError) { console.error('Error counting news directly:', newsError); } // Also count news from the junction table // First, get published news IDs const { data: publishedNews } = await supabase .from('news') .select('id') .eq('published', true); const publishedNewsIds = publishedNews ? publishedNews.map(item => item.id) : []; // Then count news from junction table where news_id is in published news IDs let newsJunctionCount = 0; if (publishedNewsIds.length > 0) { const { count: junctionCount, error: junctionError } = await supabase .from('news_categories') .select('*', { count: 'exact', head: true }) .eq('category_id', targetCategory.id) .in('news_id', publishedNewsIds); if (junctionError) { console.error('Error counting news from junction table:', junctionError); } else { newsJunctionCount = junctionCount || 0; } } // Use the larger count to avoid undercounting - using the previously defined variable const actualNewsCount = Math.max(directNewsCount || 0, newsJunctionCount); // Count learning const { count: actualLearningCount, error: learningError } = await supabase .from('learning') .select('*', { count: 'exact', head: true }) .eq('primary_category_id', targetCategory.id); if (learningError) { console.error('Error counting learning resources:', learningError); } // Count posts const { count: actualPostsCount, error: postsError } = await supabase .from('posts') .select('*', { count: 'exact', head: true }) .eq('primary_category_id', targetCategory.id) .eq('published', true); if (postsError) { console.error('Error counting posts:', postsError); } // Prepare report console.log('Count comparison:'); console.log(`Tools: API = ${targetCategory.tools_count}, DB = ${actualToolsCount || 0}`); console.log(`News: API = ${targetCategory.news_count}, DB = ${actualNewsCount || 0}`); console.log(`Learning: API = ${targetCategory.learning_count}, DB = ${actualLearningCount || 0}`); console.log(`Posts: API = ${targetCategory.posts_count}, DB = ${actualPostsCount || 0}`); // Check if counts match const toolsMatch = targetCategory.tools_count === (actualToolsCount || 0); const newsMatch = targetCategory.news_count === (actualNewsCount || 0); const learningMatch = targetCategory.learning_count === (actualLearningCount || 0); const postsMatch = targetCategory.posts_count === (actualPostsCount || 0); if (toolsMatch && newsMatch && learningMatch && postsMatch) { console.log('✅ All counts match the database values'); } else { console.error('❌ Some counts do not match the database:'); if (!toolsMatch) console.error(` - Tools count mismatch: API = ${targetCategory.tools_count}, DB = ${actualToolsCount || 0}`); if (!newsMatch) console.error(` - News count mismatch: API = ${targetCategory.news_count}, DB = ${actualNewsCount || 0}`); if (!learningMatch) console.error(` - Learning count mismatch: API = ${targetCategory.learning_count}, DB = ${actualLearningCount || 0}`); if (!postsMatch) console.error(` - Posts count mismatch: API = ${targetCategory.posts_count}, DB = ${actualPostsCount || 0}`); } } console.log('\nCategories API test completed successfully'); } catch (error) { console.error('Error during testing:', error); } } // Run the test testCategoriesApi() .then(() => { console.log('Testing completed'); process.exit(0); }) .catch((error) => { console.error('Testing failed:', error); process.exit(1); });