feat(jump-hop): redesign sling platform gameplay
This commit is contained in:
85
src/services/jump-hop/useJumpHopLeaderboard.ts
Normal file
85
src/services/jump-hop/useJumpHopLeaderboard.ts
Normal file
@@ -0,0 +1,85 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
|
||||
import {
|
||||
BACKGROUND_AUTH_REQUEST_OPTIONS,
|
||||
getStoredAccessToken,
|
||||
} from '../apiClient';
|
||||
import { ensureRuntimeGuestToken } from '../authService';
|
||||
import {
|
||||
jumpHopClient,
|
||||
type JumpHopLeaderboardResponse,
|
||||
type JumpHopRuntimeRequestOptions,
|
||||
} from './jumpHopClient';
|
||||
|
||||
type JumpHopLeaderboardState = {
|
||||
leaderboard: JumpHopLeaderboardResponse | null;
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
refresh: () => Promise<void>;
|
||||
};
|
||||
|
||||
export function useJumpHopLeaderboard(
|
||||
profileId: string | null | undefined,
|
||||
runtimeRequestOptions?: JumpHopRuntimeRequestOptions,
|
||||
): JumpHopLeaderboardState {
|
||||
const normalizedProfileId = profileId?.trim() ?? '';
|
||||
const [leaderboard, setLeaderboard] =
|
||||
useState<JumpHopLeaderboardResponse | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const refresh = useMemo(
|
||||
() => async () => {
|
||||
if (!normalizedProfileId) {
|
||||
setLeaderboard(null);
|
||||
setError(null);
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
if (runtimeRequestOptions) {
|
||||
const response = await jumpHopClient.getLeaderboard(
|
||||
normalizedProfileId,
|
||||
runtimeRequestOptions,
|
||||
);
|
||||
setLeaderboard(response);
|
||||
return;
|
||||
}
|
||||
|
||||
if (getStoredAccessToken()) {
|
||||
const response = await jumpHopClient.getLeaderboard(
|
||||
normalizedProfileId,
|
||||
BACKGROUND_AUTH_REQUEST_OPTIONS,
|
||||
);
|
||||
setLeaderboard(response);
|
||||
return;
|
||||
}
|
||||
|
||||
const runtimeGuest = await ensureRuntimeGuestToken();
|
||||
const response = await jumpHopClient.getLeaderboard(
|
||||
normalizedProfileId,
|
||||
{ runtimeGuestToken: runtimeGuest.token },
|
||||
);
|
||||
setLeaderboard(response);
|
||||
} catch (caughtError) {
|
||||
setError(
|
||||
caughtError instanceof Error
|
||||
? caughtError.message
|
||||
: '读取排行榜失败。',
|
||||
);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
},
|
||||
[normalizedProfileId, runtimeRequestOptions],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh();
|
||||
}, [refresh]);
|
||||
|
||||
return { leaderboard, isLoading, error, refresh };
|
||||
}
|
||||
Reference in New Issue
Block a user