55 lines
2.1 KiB
TypeScript
55 lines
2.1 KiB
TypeScript
import { useEffect, useRef } from "react";
|
|
import { useQueryClient, type QueryClient } from "@tanstack/react-query";
|
|
import { ApiRequestError } from "../../../shared/api";
|
|
import { useGetCurrentSession } from "../../../shared/api/endpoints/identity/identity";
|
|
import type { Session } from "../../../shared/api/schemas";
|
|
import { actorIdentity, trackActorIdentity, type ActorIdentity } from "./actor-transition";
|
|
import { isCurrentAssessmentSession } from "./session";
|
|
|
|
export type AssessmentActor = {
|
|
readonly queryClient: QueryClient;
|
|
readonly session: ReturnType<typeof useGetCurrentSession>;
|
|
/** The signed-in session, or undefined until the server answers. */
|
|
readonly actor: Session | undefined;
|
|
/** True when the cached session is the successful candidate session. */
|
|
readonly actorReady: boolean;
|
|
};
|
|
|
|
/** Access loss as the API reports it: no session, no right, or not the owner. */
|
|
export function isAssessmentAccessLoss(error: unknown): error is ApiRequestError {
|
|
return error instanceof ApiRequestError && [401, 403, 404].includes(error.status);
|
|
}
|
|
|
|
/** The session itself is gone: only a 401 means that. */
|
|
export function isAssessmentSessionEnded(error: unknown): error is ApiRequestError {
|
|
return error instanceof ApiRequestError && error.status === 401;
|
|
}
|
|
|
|
/**
|
|
* Current candidate session for the assessment screens. Cached assessment
|
|
* data is private to one session: when the account or its session token
|
|
* changes, or the session ends, every cached assessment query is dropped so
|
|
* the next account never sees it.
|
|
*/
|
|
export function useAssessmentActor(): AssessmentActor {
|
|
const queryClient = useQueryClient();
|
|
const session = useGetCurrentSession({ query: { retry: false } });
|
|
const actor = session.data;
|
|
const actorReady = Boolean(
|
|
actor &&
|
|
actor.account.scenario === "candidate" &&
|
|
isCurrentAssessmentSession(queryClient, actor),
|
|
);
|
|
const previous = useRef<ActorIdentity | null>(null);
|
|
|
|
useEffect(() => {
|
|
previous.current = trackActorIdentity(
|
|
queryClient,
|
|
previous.current,
|
|
actorIdentity(actor, actorReady),
|
|
);
|
|
}, [actor, actorReady, queryClient]);
|
|
|
|
return { queryClient, session, actor, actorReady };
|
|
}
|