Files
threeonecheck_web/utils/identitySwitch.js
2026-07-27 09:27:22 +08:00

57 lines
1.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { switchIdentity } from '@/request/identity.js';
import { getProfileDetail } from '@/request/three_one_api/info.js';
import { saveUserInfoToStorage } from '@/utils/userInfo.js';
function unwrapPayload(res) {
if (!res) return {};
const data = res.data;
if (data && typeof data === 'object' && (
data.token ||
data.identities ||
data.currentIdentity ||
data.roles
)) {
return data;
}
return res;
}
/** 根据个人信息接口刷新本地 userInfo */
export async function refreshUserInfoStorage() {
const res = await getProfileDetail();
if (res.code === 0 && res.data) {
return saveUserInfoToStorage(res.data);
}
return null;
}
/** 执行身份切换:更新 token再通过 profile 接口刷新 userInfo */
export async function performIdentitySwitch(identityId) {
const res = await switchIdentity(identityId);
const payload = unwrapPayload(res);
if (payload.token) {
uni.setStorageSync('token', payload.token);
}
if (payload.currentIdentity) {
uni.setStorageSync('currentIdentity', JSON.stringify(payload.currentIdentity));
}
await refreshUserInfoStorage();
return payload;
}
/** 切换成功后重启到首页,清空页面栈 */
export function reLaunchAfterSwitch() {
uni.showToast({
title: '身份切换成功',
icon: 'success'
});
setTimeout(() => {
uni.reLaunch({
url: '/pages/index/index'
});
}, 1500);
}