Blame view

稻城亚丁小程序/uniapp/src/utils/userProfileStorage.ts 1.61 KB
bc518174   王天杨   提交两个项目文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
  /** 本地资料(可后续对接登录用户接口) */
  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);
  }