/** * 使用生成的API的示例 */ import { buildApiCollection } from '../src/runtime' import apiConfigs from '../dist/.temp/generated/openapi3/testApi3-configs.json' import type { testApi3 } from '../dist/.temp/generated/openapi3/testApi3-types' // 创建API实例 export const api = buildApiCollection(apiConfigs) // 使用示例 async function examples() { try { // 1. 获取用户列表 console.log('📋 获取用户列表...') const users = await api.users.get({ page: 1, size: 10 }) console.log('用户列表:', users) // 2. 创建新用户 console.log('👤 创建新用户...') const newUser = await api.users.post({ name: 'John Doe', email: 'john@example.com', avatar: 'https://example.com/avatar.jpg' }) console.log('新用户:', newUser) // 3. 获取用户详情 console.log('🔍 获取用户详情...') const userDetail = await api.users.getById(newUser.id) console.log('用户详情:', userDetail) // 4. 更新用户信息 console.log('✏️ 更新用户信息...') const updatedUser = await api.users.putById(newUser.id, { name: 'John Smith', status: 'active' }) console.log('更新后用户:', updatedUser) // 5. 获取文章列表 console.log('📰 获取文章列表...') const posts = await api.posts.get() console.log('文章列表:', posts) // 6. 删除用户 console.log('🗑️ 删除用户...') await api.users.deleteById(newUser.id) console.log('用户已删除') } catch (error) { console.error('❌ API调用失败:', error) } } // 展示类型提示功能 function typeHintDemo() { // TypeScript会提供完整的类型提示和检查 // ✅ 正确的用法 api.users.get({ page: 1, size: 10 }) api.users.post({ name: 'John', email: 'john@example.com' }) api.users.getById(123) // ❌ 错误的用法(TypeScript会报错) // api.users.get({ invalidParam: 'value' }) // 参数类型错误 // api.users.post({ name: 'John' }) // 缺少必需参数email // api.users.getById('invalid') // 参数类型错误,应该是number } // 自定义配置示例 export const apiWithCustomConfig = buildApiCollection( apiConfigs, {}, // 现有API对象 { // 全局请求配置 headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer your-token-here' }, // 全局插件 plugins: [ // 可以添加日志插件等 ], // 自定义响应解析 parseResponseFunc: (response) => { // 自定义响应解析逻辑 if (response.code === 0) { return { success: true, data: response.data } } else { return { success: false, message: response.message || '请求失败', code: response.code } } } } ) // 错误处理示例 async function errorHandlingExample() { try { const user = await api.users.getById(999) // 假设用户不存在 console.log(user) } catch (error: any) { if (error.code === 404) { console.log('用户不存在') } else if (error.code === 401) { console.log('未授权访问') } else { console.log('其他错误:', error.message) } } } // 轮询示例 import { pollingApi } from '../src/runtime' function pollingExample() { // 轮询获取用户列表 const stopPolling = pollingApi( () => api.users.get({ page: 1, size: 10 }), { interval: 5000, // 5秒间隔 times: 10, // 最多轮询10次 onResponse: (users) => { console.log('轮询结果:', users) // 如果满足某个条件,返回true停止轮询 return users.length > 100 }, onError: (error) => { console.error('轮询出错:', error) // 返回true继续轮询,false停止轮询 return false } } ) // 10秒后手动停止轮询 setTimeout(() => { stopPolling() console.log('轮询已停止') }, 10000) } export { examples, typeHintDemo, errorHandlingExample, pollingExample }