299 lines
		
	
	
		
			8.3 KiB
		
	
	
	
		
			JavaScript
		
	
	
	
			
		
		
	
	
			299 lines
		
	
	
		
			8.3 KiB
		
	
	
	
		
			JavaScript
		
	
	
	
| // API 测试示例脚本
 | ||
| // 演示如何使用 Hyperdrive API 进行 CRUD 操作
 | ||
| 
 | ||
| const API_BASE_URL = 'https://hyperdrive-neondb-test.<your-subdomain>.workers.dev';
 | ||
| const API_KEY = 'your-api-key'; // 可选,如果设置了 API_SECRET
 | ||
| 
 | ||
| // 通用请求函数
 | ||
| async function apiRequest(endpoint, options = {}) {
 | ||
|   const url = `${API_BASE_URL}${endpoint}`;
 | ||
|   const headers = {
 | ||
|     'Content-Type': 'application/json',
 | ||
|     ...(API_KEY && { 'X-API-Key': API_KEY }),
 | ||
|     ...options.headers
 | ||
|   };
 | ||
|   
 | ||
|   try {
 | ||
|     const response = await fetch(url, {
 | ||
|       ...options,
 | ||
|       headers
 | ||
|     });
 | ||
|     
 | ||
|     const data = await response.json();
 | ||
|     
 | ||
|     if (!response.ok) {
 | ||
|       throw new Error(`API Error: ${data.message || response.statusText}`);
 | ||
|     }
 | ||
|     
 | ||
|     return data;
 | ||
|   } catch (error) {
 | ||
|     console.error(`Request failed for ${endpoint}:`, error.message);
 | ||
|     throw error;
 | ||
|   }
 | ||
| }
 | ||
| 
 | ||
| // API 测试函数
 | ||
| class ApiTester {
 | ||
|   static async testHealthCheck() {
 | ||
|     console.log('\n🏥 Testing health check...');
 | ||
|     try {
 | ||
|       const result = await apiRequest('/health');
 | ||
|       console.log('✅ Health check passed:', result.data);
 | ||
|       return true;
 | ||
|     } catch (error) {
 | ||
|       console.log('❌ Health check failed:', error.message);
 | ||
|       return false;
 | ||
|     }
 | ||
|   }
 | ||
|   
 | ||
|   static async initializeDatabase() {
 | ||
|     console.log('\n🗄️ Initializing database...');
 | ||
|     try {
 | ||
|       const result = await apiRequest('/init', { method: 'POST' });
 | ||
|       console.log('✅ Database initialized:', result.message);
 | ||
|       return true;
 | ||
|     } catch (error) {
 | ||
|       console.log('❌ Database initialization failed:', error.message);
 | ||
|       return false;
 | ||
|     }
 | ||
|   }
 | ||
|   
 | ||
|   static async createUser(name, email) {
 | ||
|     console.log(`\n👤 Creating user: ${name} (${email})...`);
 | ||
|     try {
 | ||
|       const result = await apiRequest('/users', {
 | ||
|         method: 'POST',
 | ||
|         body: JSON.stringify({ name, email })
 | ||
|       });
 | ||
|       console.log('✅ User created:', result.data);
 | ||
|       return result.data;
 | ||
|     } catch (error) {
 | ||
|       console.log('❌ User creation failed:', error.message);
 | ||
|       return null;
 | ||
|     }
 | ||
|   }
 | ||
|   
 | ||
|   static async getUsers(page = 1, limit = 10, search = null) {
 | ||
|     console.log(`\n📋 Getting users (page ${page}, limit ${limit}${search ? `, search: ${search}` : ''})...`);
 | ||
|     try {
 | ||
|       let endpoint = `/users?page=${page}&limit=${limit}`;
 | ||
|       if (search) endpoint += `&search=${encodeURIComponent(search)}`;
 | ||
|       
 | ||
|       const result = await apiRequest(endpoint);
 | ||
|       console.log('✅ Users retrieved:', {
 | ||
|         count: result.data.length,
 | ||
|         total: result.meta.total,
 | ||
|         users: result.data.map(u => `${u.name} (${u.email})`)
 | ||
|       });
 | ||
|       return result;
 | ||
|     } catch (error) {
 | ||
|       console.log('❌ Failed to get users:', error.message);
 | ||
|       return null;
 | ||
|     }
 | ||
|   }
 | ||
|   
 | ||
|   static async getUserById(id) {
 | ||
|     console.log(`\n🔍 Getting user by ID: ${id}...`);
 | ||
|     try {
 | ||
|       const result = await apiRequest(`/users/${id}`);
 | ||
|       console.log('✅ User found:', result.data);
 | ||
|       return result.data;
 | ||
|     } catch (error) {
 | ||
|       console.log('❌ Failed to get user:', error.message);
 | ||
|       return null;
 | ||
|     }
 | ||
|   }
 | ||
|   
 | ||
|   static async updateUser(id, updates) {
 | ||
|     console.log(`\n✏️ Updating user ${id}:`, updates);
 | ||
|     try {
 | ||
|       const result = await apiRequest(`/users/${id}`, {
 | ||
|         method: 'PUT',
 | ||
|         body: JSON.stringify(updates)
 | ||
|       });
 | ||
|       console.log('✅ User updated:', result.data);
 | ||
|       return result.data;
 | ||
|     } catch (error) {
 | ||
|       console.log('❌ Failed to update user:', error.message);
 | ||
|       return null;
 | ||
|     }
 | ||
|   }
 | ||
|   
 | ||
|   static async deleteUser(id) {
 | ||
|     console.log(`\n🗑️ Deleting user ${id}...`);
 | ||
|     try {
 | ||
|       const result = await apiRequest(`/users/${id}`, { method: 'DELETE' });
 | ||
|       console.log('✅ User deleted:', result.message);
 | ||
|       return true;
 | ||
|     } catch (error) {
 | ||
|       console.log('❌ Failed to delete user:', error.message);
 | ||
|       return false;
 | ||
|     }
 | ||
|   }
 | ||
|   
 | ||
|   static async getApiDocs() {
 | ||
|     console.log('\n📚 Getting API documentation...');
 | ||
|     try {
 | ||
|       const result = await apiRequest('/docs');
 | ||
|       console.log('✅ API Documentation:');
 | ||
|       console.log('Endpoints:', result.data.endpoints);
 | ||
|       console.log('Authentication:', result.data.authentication);
 | ||
|       console.log('Examples:', result.data.examples);
 | ||
|       return result.data;
 | ||
|     } catch (error) {
 | ||
|       console.log('❌ Failed to get API docs:', error.message);
 | ||
|       return null;
 | ||
|     }
 | ||
|   }
 | ||
| }
 | ||
| 
 | ||
| // 完整的测试流程
 | ||
| async function runFullTest() {
 | ||
|   console.log('🚀 Starting Hyperdrive API Test Suite');
 | ||
|   console.log('=====================================');
 | ||
|   
 | ||
|   // 1. 健康检查
 | ||
|   const healthOk = await ApiTester.testHealthCheck();
 | ||
|   if (!healthOk) {
 | ||
|     console.log('\n❌ Health check failed. Please check your deployment.');
 | ||
|     return;
 | ||
|   }
 | ||
|   
 | ||
|   // 2. 获取 API 文档
 | ||
|   await ApiTester.getApiDocs();
 | ||
|   
 | ||
|   // 3. 初始化数据库
 | ||
|   await ApiTester.initializeDatabase();
 | ||
|   
 | ||
|   // 4. 创建测试用户
 | ||
|   const user1 = await ApiTester.createUser('张三', 'zhangsan@example.com');
 | ||
|   const user2 = await ApiTester.createUser('李四', 'lisi@example.com');
 | ||
|   const user3 = await ApiTester.createUser('王五', 'wangwu@example.com');
 | ||
|   
 | ||
|   if (!user1 || !user2 || !user3) {
 | ||
|     console.log('\n❌ Failed to create test users.');
 | ||
|     return;
 | ||
|   }
 | ||
|   
 | ||
|   // 5. 获取用户列表
 | ||
|   await ApiTester.getUsers();
 | ||
|   
 | ||
|   // 6. 搜索用户
 | ||
|   await ApiTester.getUsers(1, 10, '张');
 | ||
|   
 | ||
|   // 7. 获取单个用户
 | ||
|   await ApiTester.getUserById(user1.id);
 | ||
|   
 | ||
|   // 8. 更新用户
 | ||
|   await ApiTester.updateUser(user1.id, {
 | ||
|     name: '张三丰',
 | ||
|     email: 'zhangsanfeng@example.com'
 | ||
|   });
 | ||
|   
 | ||
|   // 9. 验证更新
 | ||
|   await ApiTester.getUserById(user1.id);
 | ||
|   
 | ||
|   // 10. 分页测试
 | ||
|   await ApiTester.getUsers(1, 2); // 第一页,每页2条
 | ||
|   await ApiTester.getUsers(2, 2); // 第二页,每页2条
 | ||
|   
 | ||
|   // 11. 删除用户
 | ||
|   await ApiTester.deleteUser(user3.id);
 | ||
|   
 | ||
|   // 12. 验证删除
 | ||
|   await ApiTester.getUserById(user3.id); // 应该返回 404
 | ||
|   
 | ||
|   // 13. 最终用户列表
 | ||
|   await ApiTester.getUsers();
 | ||
|   
 | ||
|   console.log('\n🎉 API Test Suite Completed!');
 | ||
|   console.log('============================');
 | ||
| }
 | ||
| 
 | ||
| // 性能测试
 | ||
| async function performanceTest() {
 | ||
|   console.log('\n⚡ Performance Test');
 | ||
|   console.log('==================');
 | ||
|   
 | ||
|   const startTime = Date.now();
 | ||
|   const promises = [];
 | ||
|   
 | ||
|   // 并发创建10个用户
 | ||
|   for (let i = 0; i < 10; i++) {
 | ||
|     promises.push(
 | ||
|       ApiTester.createUser(`测试用户${i}`, `test${i}@example.com`)
 | ||
|     );
 | ||
|   }
 | ||
|   
 | ||
|   try {
 | ||
|     const results = await Promise.all(promises);
 | ||
|     const endTime = Date.now();
 | ||
|     const duration = endTime - startTime;
 | ||
|     
 | ||
|     console.log(`✅ Created ${results.filter(r => r).length} users in ${duration}ms`);
 | ||
|     console.log(`📊 Average: ${(duration / 10).toFixed(2)}ms per user`);
 | ||
|     
 | ||
|     // 清理测试数据
 | ||
|     console.log('\n🧹 Cleaning up test data...');
 | ||
|     for (const user of results.filter(r => r)) {
 | ||
|       await ApiTester.deleteUser(user.id);
 | ||
|     }
 | ||
|     
 | ||
|   } catch (error) {
 | ||
|     console.log('❌ Performance test failed:', error.message);
 | ||
|   }
 | ||
| }
 | ||
| 
 | ||
| // 错误处理测试
 | ||
| async function errorHandlingTest() {
 | ||
|   console.log('\n🚨 Error Handling Test');
 | ||
|   console.log('======================');
 | ||
|   
 | ||
|   // 测试无效数据
 | ||
|   console.log('\n Testing invalid user data...');
 | ||
|   await ApiTester.createUser('', 'invalid-email'); // 应该失败
 | ||
|   
 | ||
|   // 测试不存在的用户
 | ||
|   console.log('\n Testing non-existent user...');
 | ||
|   await ApiTester.getUserById(99999); // 应该返回 404
 | ||
|   
 | ||
|   // 测试无效的更新
 | ||
|   console.log('\n Testing invalid update...');
 | ||
|   await ApiTester.updateUser(99999, { name: 'Test' }); // 应该返回 404
 | ||
| }
 | ||
| 
 | ||
| // 主函数
 | ||
| async function main() {
 | ||
|   console.log('请确保已经部署了 Worker 并更新了 API_BASE_URL');
 | ||
|   console.log('如果设置了 API_SECRET,请更新 API_KEY 变量\n');
 | ||
|   
 | ||
|   try {
 | ||
|     await runFullTest();
 | ||
|     await performanceTest();
 | ||
|     await errorHandlingTest();
 | ||
|   } catch (error) {
 | ||
|     console.error('\n💥 Test suite failed:', error.message);
 | ||
|   }
 | ||
| }
 | ||
| 
 | ||
| // 如果直接运行此脚本
 | ||
| if (typeof window === 'undefined') {
 | ||
|   // Node.js 环境
 | ||
|   const fetch = require('node-fetch');
 | ||
|   global.fetch = fetch;
 | ||
|   main();
 | ||
| } else {
 | ||
|   // 浏览器环境
 | ||
|   console.log('在浏览器控制台中运行: main()');
 | ||
| }
 | ||
| 
 | ||
| // 导出函数供其他模块使用
 | ||
| if (typeof module !== 'undefined' && module.exports) {
 | ||
|   module.exports = {
 | ||
|     ApiTester,
 | ||
|     runFullTest,
 | ||
|     performanceTest,
 | ||
|     errorHandlingTest,
 | ||
|     main
 | ||
|   };
 | ||
| } |