userProfileStorage.ts 1.61 KB
/** 本地资料(可后续对接登录用户接口) */
export const USER_PROFILE_STORAGE_KEY = "userProfileV1";

export interface UserProfile {
  nickname: string;
  bio: string;
  /** 本地临时路径或网络图;空则用昵称首字头像 */
  avatarUrl: string;
  gender: "secret" | "male" | "female";
  /** 接口同步;仅手机号注册/登录用户有值 */
  phone: string;
}

export function defaultUserProfile(): UserProfile {
  return {
    nickname: "山行者",
    bio: "记录稻城的每一个美好瞬间",
    avatarUrl: "",
    gender: "secret",
    phone: "",
  };
}

function normalizeGender(v: unknown): UserProfile["gender"] {
  return v === "male" || v === "female" || v === "secret" ? v : "secret";
}

export function loadUserProfile(): UserProfile {
  const d = defaultUserProfile();
  try {
    const raw = uni.getStorageSync(USER_PROFILE_STORAGE_KEY);
    if (raw && typeof raw === "string") {
      const o = JSON.parse(raw) as Record<string, unknown>;
      return {
        nickname: typeof o.nickname === "string" ? o.nickname : d.nickname,
        bio: typeof o.bio === "string" ? o.bio : d.bio,
        avatarUrl: typeof o.avatarUrl === "string" ? o.avatarUrl : d.avatarUrl,
        gender: normalizeGender(o.gender),
        phone: typeof o.phone === "string" ? o.phone : d.phone,
      };
    }
  } catch {
    /* ignore */
  }
  return d;
}

export function saveUserProfile(p: UserProfile) {
  uni.setStorageSync(USER_PROFILE_STORAGE_KEY, JSON.stringify(p));
}

export function profileAvatarLetter(nickname: string): string {
  const t = nickname.trim();
  if (!t) return "游";
  return t.slice(0, 1);
}