profileApi.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // 客服个人资料 API 服务
  2. import { API_BASE_URL } from "@/lib/config";
  3. import { Profile } from "../types";
  4. // 获取个人资料
  5. export async function fetchProfile(userId: number): Promise<Profile | null> {
  6. const res = await fetch(`${API_BASE_URL}/agent/profile/${userId}`, {
  7. cache: "no-store",
  8. });
  9. if (!res.ok) {
  10. const error = await res.json().catch(() => ({}));
  11. throw new Error(
  12. error.error || error.message || `获取个人资料失败 (${res.status})`
  13. );
  14. }
  15. const data = await res.json();
  16. return {
  17. id: data.id ?? 0,
  18. username: data.username ?? "",
  19. role: data.role ?? "",
  20. avatar_url: data.avatar_url ?? "",
  21. nickname: data.nickname ?? "",
  22. email: data.email ?? "",
  23. };
  24. }
  25. // 更新个人资料
  26. export interface UpdateProfilePayload {
  27. nickname?: string;
  28. email?: string;
  29. }
  30. export async function updateProfile(
  31. userId: number,
  32. payload: UpdateProfilePayload
  33. ): Promise<Profile> {
  34. const res = await fetch(`${API_BASE_URL}/agent/profile/${userId}`, {
  35. method: "PUT",
  36. headers: { "Content-Type": "application/json" },
  37. body: JSON.stringify(payload),
  38. });
  39. if (!res.ok) {
  40. const error = await res.json().catch(() => ({}));
  41. throw new Error(
  42. error.error || error.message || `更新个人资料失败 (${res.status})`
  43. );
  44. }
  45. const data = await res.json();
  46. return {
  47. id: data.id ?? 0,
  48. username: data.username ?? "",
  49. role: data.role ?? "",
  50. avatar_url: data.avatar_url ?? "",
  51. nickname: data.nickname ?? "",
  52. email: data.email ?? "",
  53. };
  54. }
  55. // 上传头像
  56. export async function uploadAvatar(
  57. userId: number,
  58. file: File
  59. ): Promise<Profile> {
  60. const formData = new FormData();
  61. formData.append("avatar", file);
  62. const res = await fetch(`${API_BASE_URL}/agent/avatar/${userId}`, {
  63. method: "POST",
  64. body: formData,
  65. });
  66. if (!res.ok) {
  67. const error = await res.json().catch(() => ({}));
  68. throw new Error(
  69. error.error || error.message || `上传头像失败 (${res.status})`
  70. );
  71. }
  72. const data = await res.json();
  73. return {
  74. id: data.id ?? 0,
  75. username: data.username ?? "",
  76. role: data.role ?? "",
  77. avatar_url: data.avatar_url ?? "",
  78. nickname: data.nickname ?? "",
  79. email: data.email ?? "",
  80. };
  81. }