user-info-api.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { apiPost } from "@/lib/api";
  2. import { parseLevelLabel, type UserLevel } from "@/lib/user-level";
  3. export type CustomUserInfo = {
  4. name: string;
  5. phone: string;
  6. identity: string;
  7. email?: string;
  8. levelLabel?: UserLevel;
  9. referralCode?: string;
  10. };
  11. export async function updateUserInfo(input: {
  12. name: string;
  13. phone: string;
  14. identity: string;
  15. }): Promise<void> {
  16. await apiPost("/custom/update/info", {
  17. name: input.name,
  18. phone: input.phone,
  19. identity: input.identity,
  20. });
  21. }
  22. function pickString(v: unknown): string {
  23. return typeof v === "string" ? v.trim() : String(v ?? "").trim();
  24. }
  25. export async function fetchCustomUserInfo(): Promise<CustomUserInfo> {
  26. const raw = await apiPost<unknown>("/custom/info", {});
  27. const root = raw && typeof raw === "object" ? (raw as Record<string, unknown>) : {};
  28. const data =
  29. root.data && typeof root.data === "object" && root.data !== null
  30. ? (root.data as Record<string, unknown>)
  31. : root;
  32. const levelRaw = data.levelLabel ?? root.levelLabel;
  33. const levelLabel = parseLevelLabel(levelRaw) ?? undefined;
  34. const referralCode =
  35. pickString(data.referralCode ?? root.referralCode) || undefined;
  36. return {
  37. name: pickString(data.name ?? data.nickname ?? root.name ?? root.nickname),
  38. phone: pickString(data.phone ?? data.mobile ?? root.phone ?? root.mobile),
  39. identity: pickString(data.identity ?? data.idCard ?? root.identity ?? root.idCard),
  40. email: pickString(data.email ?? data.loginName ?? root.email ?? root.loginName) || undefined,
  41. levelLabel,
  42. referralCode,
  43. };
  44. }
  45. /** 静默拉取用户信息,接口失败时返回 null,避免阻断页面渲染 */
  46. export async function tryFetchCustomUserInfo(): Promise<CustomUserInfo | null> {
  47. try {
  48. return await fetchCustomUserInfo();
  49. } catch {
  50. return null;
  51. }
  52. }