AI Resource Pro / website / scripts / test-categories-api.ts
| 1 | import fetch from 'node-fetch'; |
| 2 | import { createClient } from '@supabase/supabase-js'; |
| 3 | import * as dotenv from 'dotenv'; |
| 4 | import * as path from 'path'; |
| 5 | import * as fs from 'fs'; |
| 6 | |
| 7 | // Load environment variables |
| 8 | const envLocalPath = path.resolve(process.cwd(), '../.env.local'); |
| 9 | if (fs.existsSync(envLocalPath)) { |
| 10 | console.log(`Loading environment from: ${envLocalPath}`); |
| 11 | dotenv.config({ path: envLocalPath }); |
| 12 | } else { |
| 13 | console.log(`No .env.local file found at: ${envLocalPath}`); |
| 14 | dotenv.config(); // Try loading from default .env |
| 15 | } |
| 16 | |
| 17 | // Define types for the API response |
| 18 | interface Category { |
| 19 | id: number; |
| 20 | name: string; |
| 21 | slug: string; |
| 22 | icon: string; |
| 23 | description: string; |
| 24 | tools_count: number; |
| 25 | news_count: number; |
| 26 | learning_count: number; |
| 27 | posts_count: number; |
| 28 | total_count: number; |
| 29 | counts?: { |
| 30 | tools: number; |
| 31 | news: number; |
| 32 | learning: number; |
| 33 | posts: number; |
| 34 | total: number; |
| 35 | }; |
| 36 | [key: string]: any; |
| 37 | } |
| 38 | |
| 39 | async function testCategoriesApi() { |
| 40 | console.log('Testing Categories API with count fields...'); |
| 41 | |
| 42 | // Initialize Supabase client for direct database verification |
| 43 | const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL; |
| 44 | const supabaseKey = process.env.SUPABASE_SERVICE_ROLE_KEY; |
| 45 | |
| 46 | if (!supabaseUrl || !supabaseKey) { |
| 47 | console.error('Missing Supabase environment variables. Add NEXT_PUBLIC_SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY to .env.local'); |
| 48 | process.exit(1); |
| 49 | } |
| 50 | |
| 51 | const supabase = createClient(supabaseUrl, supabaseKey); |
| 52 | |
| 53 | // Adjust URL based on your local development setup |
| 54 | const baseUrl = 'http://localhost:3000'; |
| 55 | |
| 56 | try { |
| 57 | // Test 1: Basic categories request |
| 58 | console.log('\n1. Testing basic categories request...'); |
| 59 | const response = await fetch(`${baseUrl}/api/categories`); |
| 60 | |
| 61 | if (!response.ok) { |
| 62 | throw new Error(`API request failed with status ${response.status}`); |
| 63 | } |
| 64 | |
| 65 | const categories = await response.json() as Category[]; |
| 66 | |
| 67 | if (!Array.isArray(categories)) { |
| 68 | throw new Error('Expected categories to be an array'); |
| 69 | } |
| 70 | |
| 71 | console.log(`Received ${categories.length} categories`); |
| 72 | |
| 73 | // Check the first category for count fields |
| 74 | if (categories.length > 0) { |
| 75 | const firstCategory = categories[0]; |
| 76 | console.log('\nFirst category sample:'); |
| 77 | console.log(JSON.stringify(firstCategory, null, 2)); |
| 78 | |
| 79 | // Verify the count fields exist |
| 80 | const requiredFields = ['tools_count', 'news_count', 'learning_count', 'posts_count', 'total_count']; |
| 81 | const missingFields = requiredFields.filter(field => !(field in firstCategory)); |
| 82 | |
| 83 | if (missingFields.length > 0) { |
| 84 | console.error(`❌ Missing required fields: ${missingFields.join(', ')}`); |
| 85 | } else { |
| 86 | console.log('✅ All required count fields are present'); |
| 87 | } |
| 88 | } else { |
| 89 | console.log('No categories found to test'); |
| 90 | } |
| 91 | |
| 92 | // Test 2: Categories with includeCount=true |
| 93 | console.log('\n2. Testing categories with includeCount=true...'); |
| 94 | const countResponse = await fetch(`${baseUrl}/api/categories?includeCount=true`); |
| 95 | |
| 96 | if (!countResponse.ok) { |
| 97 | throw new Error(`API request failed with status ${countResponse.status}`); |
| 98 | } |
| 99 | |
| 100 | const countCategories = await countResponse.json() as Category[]; |
| 101 | |
| 102 | if (countCategories.length > 0) { |
| 103 | const category = countCategories[0]; |
| 104 | console.log('First category with includeCount=true:'); |
| 105 | console.log(JSON.stringify(category, null, 2)); |
| 106 | |
| 107 | // Check if both new top-level counts and nested counts exist |
| 108 | const hasTopLevelCounts = 'tools_count' in category; |
| 109 | const hasNestedCounts = category.counts && 'tools' in category.counts; |
| 110 | |
| 111 | if (hasTopLevelCounts && hasNestedCounts) { |
| 112 | console.log('✅ Both top-level count fields and nested counts object exist'); |
| 113 | } else if (!hasTopLevelCounts) { |
| 114 | console.error('❌ Top-level count fields are missing'); |
| 115 | } else if (!hasNestedCounts) { |
| 116 | console.error('❌ Nested counts object is missing'); |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | // Test 3: Verify count accuracy for a specific category |
| 121 | console.log('\n3. Testing count accuracy for categories with data...'); |
| 122 | |
| 123 | // Get a few categories to test (including some that may have data) |
| 124 | const categoriesToTest = [ |
| 125 | categories.find(cat => cat.name === 'Code Assistant'), |
| 126 | categories.find(cat => cat.name === 'LLMs'), |
| 127 | categories.find(cat => cat.name === 'Vector Database'), |
| 128 | categories.find(cat => cat.name === 'AI Training'), |
| 129 | categories.find(cat => cat.name === 'Image Generation') |
| 130 | ].filter(Boolean) as Category[]; |
| 131 | |
| 132 | if (categoriesToTest.length === 0) { |
| 133 | console.log('Could not find any suitable categories for testing count accuracy'); |
| 134 | return; |
| 135 | } |
| 136 | |
| 137 | console.log(`Found ${categoriesToTest.length} categories to test`); |
| 138 | |
| 139 | // Test each category |
| 140 | for (const targetCategory of categoriesToTest) { |
| 141 | console.log(`\nTesting category: ${targetCategory.name} (${targetCategory.id})`); |
| 142 | |
| 143 | // Count tools |
| 144 | let toolsQuery = supabase |
| 145 | .from('tools') |
| 146 | .select('*', { count: 'exact', head: true }) |
| 147 | .eq('category_id', targetCategory.id) |
| 148 | .eq('published', true); |
| 149 | |
| 150 | const { count: directToolsCount, error: toolsError } = await toolsQuery; |
| 151 | |
| 152 | if (toolsError) { |
| 153 | console.error('Error counting tools directly:', toolsError); |
| 154 | } |
| 155 | |
| 156 | // Also count tools from the junction table |
| 157 | // First, get published tool IDs |
| 158 | const { data: publishedTools } = await supabase |
| 159 | .from('tools') |
| 160 | .select('id') |
| 161 | .eq('published', true); |
| 162 | |
| 163 | const publishedToolIds = publishedTools ? publishedTools.map(item => item.id) : []; |
| 164 | |
| 165 | // Then count tools from junction table where tool_id is in published tool IDs |
| 166 | let toolsJunctionCount = 0; |
| 167 | if (publishedToolIds.length > 0) { |
| 168 | const { count: junctionCount, error: junctionError } = await supabase |
| 169 | .from('tools_categories') |
| 170 | .select('*', { count: 'exact', head: true }) |
| 171 | .eq('category_id', targetCategory.id) |
| 172 | .in('tool_id', publishedToolIds); |
| 173 | |
| 174 | if (junctionError) { |
| 175 | console.error('Error counting tools from junction table:', junctionError); |
| 176 | } else { |
| 177 | toolsJunctionCount = junctionCount || 0; |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | // Use the larger count to avoid undercounting |
| 182 | const actualToolsCount = Math.max(directToolsCount || 0, toolsJunctionCount); |
| 183 | |
| 184 | // Count news - using let to declare mutable variable |
| 185 | let newsQuery = supabase |
| 186 | .from('news') |
| 187 | .select('*', { count: 'exact', head: true }) |
| 188 | .eq('category_id', targetCategory.id) |
| 189 | .eq('published', true); |
| 190 | |
| 191 | const { count: directNewsCount, error: newsError } = await newsQuery; |
| 192 | |
| 193 | if (newsError) { |
| 194 | console.error('Error counting news directly:', newsError); |
| 195 | } |
| 196 | |
| 197 | // Also count news from the junction table |
| 198 | // First, get published news IDs |
| 199 | const { data: publishedNews } = await supabase |
| 200 | .from('news') |
| 201 | .select('id') |
| 202 | .eq('published', true); |
| 203 | |
| 204 | const publishedNewsIds = publishedNews ? publishedNews.map(item => item.id) : []; |
| 205 | |
| 206 | // Then count news from junction table where news_id is in published news IDs |
| 207 | let newsJunctionCount = 0; |
| 208 | if (publishedNewsIds.length > 0) { |
| 209 | const { count: junctionCount, error: junctionError } = await supabase |
| 210 | .from('news_categories') |
| 211 | .select('*', { count: 'exact', head: true }) |
| 212 | .eq('category_id', targetCategory.id) |
| 213 | .in('news_id', publishedNewsIds); |
| 214 | |
| 215 | if (junctionError) { |
| 216 | console.error('Error counting news from junction table:', junctionError); |
| 217 | } else { |
| 218 | newsJunctionCount = junctionCount || 0; |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | // Use the larger count to avoid undercounting - using the previously defined variable |
| 223 | const actualNewsCount = Math.max(directNewsCount || 0, newsJunctionCount); |
| 224 | |
| 225 | // Count learning |
| 226 | const { count: actualLearningCount, error: learningError } = await supabase |
| 227 | .from('learning') |
| 228 | .select('*', { count: 'exact', head: true }) |
| 229 | .eq('primary_category_id', targetCategory.id); |
| 230 | |
| 231 | if (learningError) { |
| 232 | console.error('Error counting learning resources:', learningError); |
| 233 | } |
| 234 | |
| 235 | // Count posts |
| 236 | const { count: actualPostsCount, error: postsError } = await supabase |
| 237 | .from('posts') |
| 238 | .select('*', { count: 'exact', head: true }) |
| 239 | .eq('primary_category_id', targetCategory.id) |
| 240 | .eq('published', true); |
| 241 | |
| 242 | if (postsError) { |
| 243 | console.error('Error counting posts:', postsError); |
| 244 | } |
| 245 | |
| 246 | // Prepare report |
| 247 | console.log('Count comparison:'); |
| 248 | console.log(`Tools: API = ${targetCategory.tools_count}, DB = ${actualToolsCount || 0}`); |
| 249 | console.log(`News: API = ${targetCategory.news_count}, DB = ${actualNewsCount || 0}`); |
| 250 | console.log(`Learning: API = ${targetCategory.learning_count}, DB = ${actualLearningCount || 0}`); |
| 251 | console.log(`Posts: API = ${targetCategory.posts_count}, DB = ${actualPostsCount || 0}`); |
| 252 | |
| 253 | // Check if counts match |
| 254 | const toolsMatch = targetCategory.tools_count === (actualToolsCount || 0); |
| 255 | const newsMatch = targetCategory.news_count === (actualNewsCount || 0); |
| 256 | const learningMatch = targetCategory.learning_count === (actualLearningCount || 0); |
| 257 | const postsMatch = targetCategory.posts_count === (actualPostsCount || 0); |
| 258 | |
| 259 | if (toolsMatch && newsMatch && learningMatch && postsMatch) { |
| 260 | console.log('✅ All counts match the database values'); |
| 261 | } else { |
| 262 | console.error('❌ Some counts do not match the database:'); |
| 263 | if (!toolsMatch) console.error(` - Tools count mismatch: API = ${targetCategory.tools_count}, DB = ${actualToolsCount || 0}`); |
| 264 | if (!newsMatch) console.error(` - News count mismatch: API = ${targetCategory.news_count}, DB = ${actualNewsCount || 0}`); |
| 265 | if (!learningMatch) console.error(` - Learning count mismatch: API = ${targetCategory.learning_count}, DB = ${actualLearningCount || 0}`); |
| 266 | if (!postsMatch) console.error(` - Posts count mismatch: API = ${targetCategory.posts_count}, DB = ${actualPostsCount || 0}`); |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | console.log('\nCategories API test completed successfully'); |
| 271 | } catch (error) { |
| 272 | console.error('Error during testing:', error); |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | // Run the test |
| 277 | testCategoriesApi() |
| 278 | .then(() => { |
| 279 | console.log('Testing completed'); |
| 280 | process.exit(0); |
| 281 | }) |
| 282 | .catch((error) => { |
| 283 | console.error('Testing failed:', error); |
| 284 | process.exit(1); |
| 285 | }); |