profile.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { ApiError, getApiUrl, requestApi, type ApiResponse } from './api'
  2. import type { UserProfile } from './auth'
  3. import { getToken } from '@/utils/auth'
  4. export interface UpdateProfilePayload {
  5. nickName: string
  6. phonenumber: string
  7. email: string
  8. sex: string
  9. }
  10. export interface AvatarResponse extends ApiResponse {
  11. imgUrl?: string
  12. }
  13. export function updateUserProfile(payload: UpdateProfilePayload) {
  14. return requestApi<ApiResponse>('/system/user/profile', {
  15. method: 'PUT',
  16. data: payload,
  17. })
  18. }
  19. export function updatePassword(oldPassword: string, newPassword: string) {
  20. return requestApi<ApiResponse>('/system/user/profile/updatePwd', {
  21. method: 'PUT',
  22. data: { oldPassword, newPassword },
  23. })
  24. }
  25. export function uploadAvatar(filePath: string): Promise<AvatarResponse> {
  26. return new Promise((resolve, reject) => {
  27. uni.uploadFile({
  28. url: getApiUrl('/system/user/profile/avatar'),
  29. filePath,
  30. name: 'avatarfile',
  31. header: { Authorization: `Bearer ${getToken()}` },
  32. timeout: 20000,
  33. success(response) {
  34. if (response.statusCode < 200 || response.statusCode >= 300) {
  35. reject(new ApiError(`系统接口 ${response.statusCode} 异常`, response.statusCode))
  36. return
  37. }
  38. try {
  39. const result = JSON.parse(response.data) as AvatarResponse
  40. const code = result.code ?? 200
  41. if (code === 200) resolve(result)
  42. else reject(new ApiError(result.msg || result.message || '头像上传失败', code))
  43. } catch {
  44. reject(new ApiError('头像上传响应格式异常'))
  45. }
  46. },
  47. fail(error) {
  48. const message = error.errMsg?.includes('timeout') ? '头像上传超时' : '头像上传失败'
  49. reject(new ApiError(message))
  50. },
  51. })
  52. })
  53. }
  54. export function resolveAvatarUrl(avatar?: UserProfile['avatar']) {
  55. if (!avatar) return ''
  56. if (/^(https?:|data:|blob:)/.test(avatar)) return avatar
  57. return getApiUrl(avatar)
  58. }