user-label-api.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { apiPost } from "@/lib/api";
  2. import { parseLevelLabel, type UserLevel } from "@/lib/user-level";
  3. export type CustomUserLabel = {
  4. levelLabel?: UserLevel;
  5. referralCode?: string;
  6. };
  7. function pickString(v: unknown): string {
  8. return typeof v === "string" ? v.trim() : String(v ?? "").trim();
  9. }
  10. export async function fetchCustomUserLabel(): Promise<CustomUserLabel> {
  11. const raw = await apiPost<unknown>("/custom/get/label", {});
  12. const root = raw && typeof raw === "object" ? (raw as Record<string, unknown>) : {};
  13. const data =
  14. root.data && typeof root.data === "object" && root.data !== null
  15. ? (root.data as Record<string, unknown>)
  16. : root;
  17. const levelRaw =
  18. data.levelLabel ?? data.level ?? data.label ?? root.levelLabel ?? root.level ?? root.label;
  19. const levelLabel = parseLevelLabel(levelRaw) ?? undefined;
  20. const referralCode =
  21. pickString(
  22. data.referralCode ??
  23. data.referral_code ??
  24. data.code ??
  25. root.referralCode ??
  26. root.referral_code ??
  27. root.code,
  28. ) || undefined;
  29. return { levelLabel, referralCode };
  30. }
  31. /** 静默拉取用户标签,接口失败时返回 null,避免阻断页面渲染 */
  32. export async function tryFetchCustomUserLabel(): Promise<CustomUserLabel | null> {
  33. try {
  34. return await fetchCustomUserLabel();
  35. } catch {
  36. return null;
  37. }
  38. }