59 lines
2.4 KiB
TypeScript
59 lines
2.4 KiB
TypeScript
import { useCallback, useEffect, useState } from 'react';
|
|
import { AgentProfileApiError, getAgentProfileApiErrorMessage } from '@/lib/agent-profile';
|
|
import { useAuthStore } from '@/stores/auth';
|
|
import { getProfileAccountKey, isUserProfileComplete, useUserProfileStore } from '@/stores/user-profile';
|
|
|
|
function getProfileSyncErrorMessage(error: unknown): string {
|
|
if (error instanceof AgentProfileApiError) {
|
|
return getAgentProfileApiErrorMessage(error);
|
|
}
|
|
return error instanceof Error ? error.message : String(error);
|
|
}
|
|
|
|
export function useCurrentUserProfile(enabled = true) {
|
|
const authUser = useAuthStore((state) => state.user);
|
|
const getValidAccessToken = useAuthStore((state) => state.getValidAccessToken);
|
|
const profilesByUserId = useUserProfileStore((state) => state.profilesByUserId);
|
|
const syncStatesByUserId = useUserProfileStore((state) => state.syncStatesByUserId);
|
|
const syncProfile = useUserProfileStore((state) => state.syncProfile);
|
|
const profileAccountKey = getProfileAccountKey(authUser?.userId ?? authUser?.username);
|
|
const userProfile = profileAccountKey ? profilesByUserId[profileAccountKey] : undefined;
|
|
const profileSyncState = profileAccountKey ? syncStatesByUserId[profileAccountKey] : undefined;
|
|
const [profileSyncError, setProfileSyncError] = useState<string | null>(null);
|
|
|
|
const syncProfileNow = useCallback(async () => {
|
|
if (!enabled || !authUser || !profileAccountKey) return null;
|
|
|
|
setProfileSyncError(null);
|
|
try {
|
|
const accessToken = await getValidAccessToken();
|
|
if (!accessToken) throw new Error('登录已过期,请重新登录后再同步个人资料。');
|
|
return await syncProfile(profileAccountKey, accessToken);
|
|
} catch (error) {
|
|
setProfileSyncError(getProfileSyncErrorMessage(error));
|
|
throw error;
|
|
}
|
|
}, [authUser, enabled, getValidAccessToken, profileAccountKey, syncProfile]);
|
|
|
|
useEffect(() => {
|
|
if (!enabled || !authUser || !profileAccountKey) {
|
|
setProfileSyncError(null);
|
|
return;
|
|
}
|
|
void syncProfileNow().catch(() => undefined);
|
|
}, [authUser, enabled, profileAccountKey, syncProfileNow]);
|
|
|
|
return {
|
|
profileAccountKey,
|
|
userProfile,
|
|
profileSyncState,
|
|
profileRequired: Boolean(
|
|
authUser
|
|
&& profileSyncState?.status === 'ready'
|
|
&& !isUserProfileComplete(userProfile),
|
|
),
|
|
profileSyncError,
|
|
syncProfileNow,
|
|
};
|
|
}
|