API 接口文档
这是在线学习平台的前端API接口封装,提供了完整的类型定义和请求方法。
📁 文件结构
src/api/
├── index.ts # 统一导出文件
├── types.ts # TypeScript 类型定义
├── request.ts # HTTP 请求封装
├── utils.ts # 工具函数
├── modules/ # API 模块
│ ├── auth.ts # 认证相关API
│ ├── course.ts # 课程相关API
│ ├── comment.ts # 评论相关API
│ ├── favorite.ts # 收藏相关API
│ ├── order.ts # 订单相关API
│ ├── upload.ts # 文件上传API
│ └── statistics.ts # 统计相关API
├── examples/ # 使用示例
│ └── usage.ts # API使用示例
└── README.md # 文档说明
🚀 快速开始
1. 环境配置
复制 .env.example
为 .env.local
并配置API地址:
cp .env.example .env.local
# API 配置
VITE_API_BASE_URL=http://localhost:3000/api
VITE_API_TIMEOUT=10000
2. 基础使用
import { AuthApi, CourseApi } from '@/api'
// 用户登录
const login = async () => {
try {
const response = await AuthApi.login({
email: 'user@example.com',
password: 'password123'
})
if (response.code === 200) {
console.log('登录成功:', response.data)
}
} catch (error) {
console.error('登录失败:', error)
}
}
// 获取课程列表
const getCourses = async () => {
try {
const response = await CourseApi.getCourses({
page: 1,
pageSize: 20,
category: '前端开发'
})
if (response.code === 200) {
console.log('课程列表:', response.data)
}
} catch (error) {
console.error('获取课程失败:', error)
}
}
📚 API 模块说明
认证模块 (AuthApi)
提供用户认证相关的所有接口:
login()
- 用户登录register()
- 用户注册logout()
- 用户登出getCurrentUser()
- 获取当前用户信息updateProfile()
- 更新用户资料changePassword()
- 修改密码uploadAvatar()
- 上传头像
课程模块 (CourseApi)
提供课程相关的所有接口:
getCourses()
- 获取课程列表searchCourses()
- 搜索课程getCourseById()
- 获取课程详情enrollCourse()
- 报名课程getLearningProgress()
- 获取学习进度getCourseChapters()
- 获取课程章节getCourseLessons()
- 获取课程课时
评论模块 (CommentApi)
提供评论相关的所有接口:
getCourseComments()
- 获取课程评论addCourseComment()
- 添加课程评论likeComment()
- 点赞评论updateComment()
- 更新评论deleteComment()
- 删除评论
收藏模块 (FavoriteApi)
提供收藏相关的所有接口:
addFavorite()
- 添加收藏removeFavorite()
- 取消收藏getMyFavorites()
- 获取收藏列表checkFavorite()
- 检查收藏状态
订单模块 (OrderApi)
提供订单相关的所有接口:
createOrder()
- 创建订单getOrders()
- 获取订单列表getOrderById()
- 获取订单详情cancelOrder()
- 取消订单confirmPayment()
- 确认支付
上传模块 (UploadApi)
提供文件上传相关的所有接口:
uploadFile()
- 上传单个文件uploadAvatar()
- 上传头像uploadCourseVideo()
- 上传课程视频uploadMultipleFiles()
- 批量上传文件
统计模块 (StatisticsApi)
提供统计相关的所有接口:
getPlatformStats()
- 获取平台统计getUserLearningStats()
- 获取用户学习统计getCourseStats()
- 获取课程统计
🔧 工具函数
请求工具
import { ApiRequest } from '@/api'
// GET 请求
const data = await ApiRequest.get('/endpoint', { param: 'value' })
// POST 请求
const result = await ApiRequest.post('/endpoint', { data: 'value' })
// 文件上传
const uploadResult = await ApiRequest.upload('/upload', file, (progress) => {
console.log('上传进度:', progress + '%')
})
工具函数
import {
buildQueryString,
formatFileSize,
formatDuration,
isValidEmail,
storage
} from '@/api/utils'
// 构建查询字符串
const query = buildQueryString({ page: 1, size: 20 })
// 格式化文件大小
const size = formatFileSize(1024000) // "1000 KB"
// 格式化时长
const duration = formatDuration(3661) // "1小时1分1秒"
// 验证邮箱
const valid = isValidEmail('user@example.com') // true
// 本地存储
storage.set('user', { id: 1, name: 'John' })
const user = storage.get('user')
🎯 类型定义
所有API都有完整的TypeScript类型定义:
import type {
User,
Course,
Comment,
Order,
ApiResponse,
PaginationResponse
} from '@/api'
// 用户类型
const user: User = {
id: 1,
username: 'john',
email: 'john@example.com',
role: 'student'
}
// API响应类型
const response: ApiResponse<User> = {
code: 200,
message: '成功',
data: user
}
// 分页响应类型
const pageResponse: ApiResponse<PaginationResponse<Course>> = {
code: 200,
message: '成功',
data: {
list: [],
total: 100,
page: 1,
pageSize: 20,
totalPages: 5
}
}
🛠️ 错误处理
全局错误处理
请求拦截器会自动处理常见错误:
- 401: 自动跳转登录页
- 403: 显示权限不足提示
- 500: 显示服务器错误提示
- 网络错误: 显示网络连接提示
自定义错误处理
import { getErrorMessage } from '@/api/utils'
try {
const response = await AuthApi.login(credentials)
} catch (error) {
const message = getErrorMessage(error)
console.error('登录失败:', message)
// 显示错误提示
}
📝 最佳实践
1. 使用TypeScript类型
import type { Course, ApiResponse } from '@/api'
const handleCourseData = (response: ApiResponse<Course[]>) => {
if (response.code === 200) {
response.data.forEach(course => {
// TypeScript 会提供完整的类型提示
console.log(course.title, course.instructor.name)
})
}
}
2. 错误边界处理
const fetchData = async () => {
try {
const response = await CourseApi.getCourses()
return response.data
} catch (error) {
// 记录错误日志
console.error('API Error:', error)
// 返回默认值或重新抛出错误
throw error
}
}
3. 加载状态管理
const loading = ref(false)
const loadCourses = async () => {
loading.value = true
try {
const response = await CourseApi.getCourses()
// 处理数据
} catch (error) {
// 处理错误
} finally {
loading.value = false
}
}
4. 分页数据处理
import { formatPaginationData } from '@/api/utils'
const loadCourses = async (page: number = 1) => {
try {
const response = await CourseApi.getCourses({ page, pageSize: 20 })
const pagination = formatPaginationData(response)
console.log('课程列表:', pagination.items)
console.log('分页信息:', {
current: pagination.currentPage,
total: pagination.totalPages,
hasNext: pagination.hasNext
})
} catch (error) {
console.error('加载失败:', error)
}
}
🔄 更新日志
v1.0.0
- 初始版本
- 完整的API接口封装
- TypeScript类型定义
- 错误处理机制
- 工具函数库