API SDK 使用指南
🚀 概述
本项目提供了两种API调用方式:
- 原始SDK (
sdk.gen.ts) - 直接API调用,无认证 - 认证SDK (
authenticated-sdk.ts) - 自动添加Token的API调用
📝 使用方法
1. 无认证的API调用(如登录、获取验证码)
import { api } from '@/lib/api/authenticated-sdk';
// 获取验证码 - 不需要token
const captchaResponse = await api.getCaptcha();
// 用户登录 - 不需要token
const loginResponse = await api.login({
body: {
identifier: 'admin',
password: 'password123',
captcha_id: 'captcha-id',
captcha_text: 'ABCD'
}
});
2. 需要认证的API调用
import { authenticatedSdk } from '@/lib/api/authenticated-sdk';
// 获取当前用户信息 - 自动添加token
const userResponse = await authenticatedSdk.getCurrentUser();
// 获取用户列表 - 自动添加token
const usersResponse = await authenticatedSdk.getUsers({
query: { page: 1, size: 10 }
});
// 创建用户 - 自动添加token
const createResponse = await authenticatedSdk.createUser({
body: {
username: 'newuser',
email: 'user@example.com'
}
});
🔧 核心特性
自动Token管理
- 自动从localStorage获取token
- 自动添加到请求头
Authorization: Bearer {token} - 请求日志记录
401错误处理
- 检测401响应自动清除本地认证信息
- 自动跳转到登录页面
类型安全
- 完整的TypeScript类型支持
- 智能代码提示
📋 API方法列表
认证相关
api.getCaptcha()- 获取验证码api.login(options)- 用户登录api.logout(options)- 用户登出authenticatedSdk.getCurrentUser()- 获取当前用户authenticatedSdk.refreshToken()- 刷新token
用户管理
authenticatedSdk.getUsers()- 获取用户列表authenticatedSdk.getUser(options)- 获取单个用户authenticatedSdk.createUser(options)- 创建用户authenticatedSdk.updateUser(options)- 更新用户authenticatedSdk.deleteUser(options)- 删除用户
部门管理
authenticatedSdk.getDepartments()- 获取部门列表authenticatedSdk.getDepartment(options)- 获取单个部门authenticatedSdk.createDepartment(options)- 创建部门authenticatedSdk.updateDepartment(options)- 更新部门authenticatedSdk.deleteDepartment(options)- 删除部门
租户管理
authenticatedSdk.getTenants()- 获取租户列表authenticatedSdk.getTenant(options)- 获取单个租户authenticatedSdk.getCurrentTenant()- 获取当前租户信息
⚠️ 重要说明
- API生成覆盖:
sdk.gen.ts和client.gen.ts会被npm run api:generate覆盖 - 安全文件:
authenticated-sdk.ts不会被覆盖,可安全使用 - Token存储: Token存储在localStorage的user对象中
- 代理配置: 所有请求通过Next.js代理到真实API地址
🔄 迁移指南
从原始SDK迁移到认证SDK
// ❌ 旧方式 - 可能缺少认证
import { getUsersApiV1UsersGet } from '@/lib/api/sdk.gen';
const response = await getUsersApiV1UsersGet();
// ✅ 新方式 - 自动添加认证
import { authenticatedSdk } from '@/lib/api/authenticated-sdk';
const response = await authenticatedSdk.getUsers();
混合使用场景
import { api, authenticatedSdk } from '@/lib/api/authenticated-sdk';
// 登录 - 不需要认证
const loginResponse = await api.login({ body: loginData });
// 登录成功后,获取用户信息 - 需要认证
const userInfo = await authenticatedSdk.getCurrentUser();