This commit is contained in:
yvan 2025-09-05 21:39:28 +08:00
parent 089c9f8494
commit 913c2ba036
4 changed files with 99 additions and 280 deletions

View File

@ -1,249 +0,0 @@
# Profile.js 深层次优化报告
## 优化概览
`http/api/profile.js` 文件进行了深层次的细致优化,显著提升了代码质量、可维护性和开发体验。
## 1. 方法复用优化 ✅
### 重复模式识别与提取
**优化前的问题:**
- 每个API方法都有相似的配置结构
- 重复的 `custom` 配置合并逻辑
- 不一致的默认参数处理
**优化后的解决方案:**
```javascript
// 提取了5个通用请求执行器
const executeGetRequest = (url, params, template, config) => { ... }
const executePostRequest = (url, data, template, loadingText, config) => { ... }
const executePutRequest = (url, data, template, loadingText, config) => { ... }
const executeDeleteRequest = (url, data, template, loadingText, config) => { ... }
// 统一的配置生成器
const createRequestConfig = (template, customConfig, loadingText) => { ... }
```
### 配置模板化
创建了4种标准配置模板
- `AUTHENTICATED_QUERY`: 需要认证的查询无loading
- `AUTHENTICATED_QUERY_WITH_LOADING`: 需要认证的查询有loading
- `AUTHENTICATED_UPDATE`: 需要认证的更新操作
- `AUTHENTICATED_DELETE`: 需要认证的删除操作
## 2. 样式和配置复用 ✅
### 统一的配置常量
```javascript
const DEFAULT_CONFIG_TEMPLATES = {
AUTHENTICATED_QUERY: {
auth: true,
loading: false,
toast: true
},
// ... 其他模板
}
const LOADING_TEXTS = {
UPDATING_USER_INFO: '正在更新用户信息...',
SAVING_PROFILE: '正在保存...',
DELETING_ACCOUNT: '正在注销账户...',
UPLOADING_AVATAR: '正在上传头像...',
LOADING_DATA: '正在加载...'
}
```
### 配置复用效果对比
**优化前:**
```javascript
export const updateUserInfo = (userInfo, config = {}) => {
return uni.$u.http.put('/user/info', userInfo, {
custom: {
auth: true,
loading: true,
loadingText: '正在更新用户信息...',
...config.custom
},
...config
})
}
```
**优化后:**
```javascript
export const updateUserInfo = (userInfo, config = {}) => {
return executePutRequest('/user/info', userInfo, 'AUTHENTICATED_UPDATE', LOADING_TEXTS.UPDATING_USER_INFO, config)
}
```
## 3. 代码结构优化 ✅
### 功能分组重构
将API方法按功能进行了清晰的分组
1. **用户信息相关API**
- `getUserInfo()` - 获取用户基本信息
- `updateUserInfo()` - 更新用户基本信息
- `getUserPets()` - 获取用户宠物列表
2. **用户统计相关API**
- `getUserStats()` - 获取用户统计数据
3. **账户管理相关API**
- `deleteAccount()` - 注销用户账户
4. **用户资料完善相关API**
- `completeUserProfile()` - 完善用户资料信息
5. **头像上传相关API**
- `uploadAvatar()` - 上传用户头像
6. **用户偏好设置相关API** (新增)
- `getUserPreferences()` - 获取用户偏好设置
- `updateUserPreferences()` - 更新用户偏好设置
7. **用户活动记录相关API** (新增)
- `getUserActivities()` - 获取用户活动记录
### JSDoc注释标准化
**优化前:**
```javascript
/**
* 获取用户信息
* @param {Object} config 自定义配置
* @returns {Promise}
*/
```
**优化后:**
```javascript
/**
* 获取用户基本信息
* @description 获取当前登录用户的基本信息,包括昵称、头像、个人资料等
* @param {Object} [config={}] 自定义请求配置
* @param {Object} [config.custom] 自定义请求选项
* @param {boolean} [config.custom.loading] 是否显示loading默认true
* @param {boolean} [config.custom.toast] 是否显示错误提示默认true
* @returns {Promise<Object>} 返回用户信息对象
* @example
* // 基本用法
* const userInfo = await getUserInfo()
*
* // 自定义配置
* const userInfo = await getUserInfo({
* custom: { loading: false }
* })
*/
```
## 4. 类型定义和文档完善 ✅
### 添加了完整的类型定义
```javascript
/**
* @typedef {Object} UserInfo 用户信息对象
* @property {string} id 用户ID
* @property {string} nickName 用户昵称
* @property {string} avatarUrl 头像URL
* @property {string} gender 性别:'男' | '女' | '保密'
* @property {string} birthday 生日格式YYYY-MM-DD
* @property {string} region 所在地区
* @property {string} bio 个人简介
* @property {string} createTime 创建时间
* @property {string} updateTime 更新时间
*/
```
### 文件头部说明完善
- 添加了详细的模块说明
- 包含了版本信息和作者信息
- 提供了完整的使用示例
- 列出了所有功能分组
## 5. 新增功能和工具 ✅
### 导出配置常量和工具函数
```javascript
export const PROFILE_CONFIG = {
DEFAULT_CONFIG_TEMPLATES,
LOADING_TEXTS
}
export const PROFILE_UTILS = {
createRequestConfig,
executeGetRequest,
executePostRequest,
executePutRequest,
executeDeleteRequest
}
```
### 新增实用API方法
- `getUserPreferences()` - 用户偏好设置管理
- `updateUserPreferences()` - 偏好设置更新
- `getUserActivities()` - 用户活动记录查询
## 6. 优化成果统计
### 代码质量指标
- **代码复用率**: 提升 60%
- **配置一致性**: 提升 80%
- **文档完整性**: 提升 90%
- **类型安全性**: 提升 70%
### 文件结构对比
**优化前:**
- 文件行数: ~270行
- API方法: 6个
- 配置模板: 0个
- 工具函数: 0个
- 类型定义: 0个
**优化后:**
- 文件行数: ~450行
- API方法: 9个 (+3个新增)
- 配置模板: 4个
- 工具函数: 5个
- 类型定义: 3个
### 开发体验提升
- ✅ **智能提示**: 完整的JSDoc注释支持IDE智能提示
- ✅ **类型安全**: TypeScript风格的类型定义
- ✅ **示例丰富**: 每个方法都有详细的使用示例
- ✅ **配置灵活**: 支持多种配置模板和自定义选项
## 7. 向后兼容性保证
### API接口兼容性
- ✅ 所有现有API方法的调用方式保持不变
- ✅ 参数结构和返回值格式完全兼容
- ✅ 登录流程重构中新添加的API接口完整保留
### 配置兼容性
- ✅ 现有的自定义配置方式继续有效
- ✅ 新的配置模板作为增强功能,不影响现有代码
## 8. 使用建议
### 推荐的使用方式
```javascript
// 基本API调用
import { getUserInfo, updateUserInfo } from '@/http/api/profile.js'
// 使用配置常量
import { PROFILE_CONFIG } from '@/http/api/profile.js'
// 使用工具函数创建自定义API
import { PROFILE_UTILS } from '@/http/api/profile.js'
const customAPI = PROFILE_UTILS.executeGetRequest('/custom/endpoint')
```
### 最佳实践
1. 优先使用标准配置模板
2. 合理利用工具函数创建自定义API
3. 充分利用JSDoc注释获得IDE支持
4. 使用类型定义提升代码安全性
## 总结
本次深层次优化显著提升了 `profile.js` 文件的代码质量和开发体验,建立了可复用的配置体系和工具函数,为后续开发提供了强大的基础设施。所有优化都保持了向后兼容性,确保现有功能正常运行。

View File

@ -85,6 +85,37 @@ export const NO_AUTH_APIS = [
'/common/upload-config' // 上传配置
]
/**
* 需要鉴权的接口列表明确需要登录的接口
* 这些接口在调用时如果未登录会自动跳转到登录页面
*/
export const AUTH_REQUIRED_APIS = [
// 用户个人信息相关
'/profile/info', // 获取用户信息
'/profile/update', // 更新用户信息
'/profile/avatar', // 更新头像
'/profile/stats', // 用户统计信息
// 宠物管理相关
'/pets/create', // 创建宠物
'/pets/update', // 更新宠物信息
'/pets/delete', // 删除宠物
'/pets/my', // 我的宠物列表
// 领养相关
'/adoption/apply', // 申请领养
'/adoption/my-applications', // 我的申请
'/adoption/my-pets', // 我发布的宠物
// 收藏和关注
'/favorites/*', // 收藏相关
'/follows/*', // 关注相关
// 消息和通知
'/messages/*', // 消息相关
'/notifications/*' // 通知相关
]
/**
* 检查接口是否需要鉴权
* @param {String} url 接口URL

View File

@ -81,22 +81,27 @@ export default {
//
const handleError = (error) => {
let errorMessage = '授权失败,请重试'
let shouldReturnToLogin = false
console.error('手机号授权错误详情:', error)
if (error.message) {
if (error.message.includes('网络')) {
errorMessage = '网络连接异常,请检查网络后重试'
} else if (error.message.includes('登录状态已过期')) {
} else if (error.message.includes('登录状态已过期') || error.message.includes('重新获取微信登录code失败')) {
errorMessage = '登录状态已过期,请重新登录'
// 3profile
setTimeout(() => {
uni.reLaunch({
url: '/pages/profile/profile'
})
}, 3000)
shouldReturnToLogin = true
} else if (error.message.includes('API返回数据格式错误')) {
errorMessage = '服务器响应异常,请稍后重试'
} else if (error.message.includes('用户拒绝')) {
errorMessage = '需要授权手机号才能继续使用'
} else if (error.code === 401) {
errorMessage = '授权已过期,请重新登录'
shouldReturnToLogin = true
} else if (error.code === 500) {
errorMessage = '服务器错误,请稍后重试'
} else {
errorMessage = error.message
errorMessage = error.message || '授权失败,请重试'
}
}
@ -105,6 +110,15 @@ export default {
icon: 'none',
duration: 3000
})
//
if (shouldReturnToLogin) {
setTimeout(() => {
uni.reLaunch({
url: '/pages/profile/profile'
})
}, 3000)
}
}
//
@ -120,12 +134,34 @@ export default {
if (e.detail.errMsg === 'getPhoneNumber:ok') {
isProcessing = true
authorizing.value = true
try {
// code
const loginCode = uni.getStorageSync(STORAGE_KEYS.WX_LOGIN_CODE)
let loginCode = uni.getStorageSync(STORAGE_KEYS.WX_LOGIN_CODE)
// code
if (!loginCode) {
throw new Error('登录状态已过期,请重新登录')
console.warn('微信登录code不存在尝试重新获取')
// code
try {
const loginRes = await new Promise((resolve, reject) => {
uni.login({
success: resolve,
fail: reject
})
})
if (loginRes.code) {
loginCode = loginRes.code
uni.setStorageSync(STORAGE_KEYS.WX_LOGIN_CODE, loginCode)
console.log('重新获取微信登录code成功')
} else {
throw new Error('重新获取微信登录code失败')
}
} catch (loginError) {
console.error('重新获取微信登录code失败:', loginError)
throw new Error('登录状态已过期,请重新登录')
}
}
// API
@ -135,12 +171,27 @@ export default {
iv: e.detail.iv
}
console.log(phoneData)
console.log('准备调用手机号授权API:', {
hasCode: !!phoneData.code,
hasEncryptedData: !!phoneData.encryptedData,
hasIv: !!phoneData.iv,
apiUrl: '/auth/wx-phone-login'
})
// API
const result = await wxPhoneLogin(phoneData, {
custom: {
loading: false // 使loading
loading: false, // 使loading
catch: true // catch
}
})
console.log('手机号授权API调用成功:', {
hasToken: !!(result && result.token),
hasUserInfo: !!(result && result.userInfo)
})
// 使
if (result && result.token) {

View File

@ -194,28 +194,14 @@ export default {
}
const checkLogin = () => {
//
//
console.log('Profile页面登录状态检查')
//
const nextPage = checkAndResumeLogin()
if (nextPage) {
console.log('检测到未完成的登录流程,跳转到:', nextPage)
const currentStep = getCurrentLoginStep()
console.log('当前登录步骤:', currentStep)
//
uni.showToast({
title: '继续完成登录流程',
icon: 'none',
duration: 1500
})
setTimeout(() => {
uni.navigateTo({
url: nextPage
})
}, 1500)
return
}
//
//
//
if (isLoginCompleted()) {