refactor: centralize frontend auth query gating
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
import { MantineProvider } from "@mantine/core";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { renderHook, waitFor } from "@testing-library/react";
|
||||
import { HttpResponse, http } from "msw";
|
||||
import type { ReactNode } from "react";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { server } from "@/test/server";
|
||||
import { useAuthenticatedQuery } from "./authenticated-query";
|
||||
import { apiQueryClient, configureAuthClient } from "./client";
|
||||
|
||||
function createWrapper() {
|
||||
const client = new QueryClient();
|
||||
return ({ children }: { children: ReactNode }) => (
|
||||
<MantineProvider>
|
||||
<QueryClientProvider client={client}>{children}</QueryClientProvider>
|
||||
</MantineProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe("useAuthenticatedQuery", () => {
|
||||
afterEach(() => configureAuthClient(null));
|
||||
|
||||
it("keeps protected queries idle without a session and loads after session configuration", async () => {
|
||||
const requests = vi.fn();
|
||||
server.use(
|
||||
http.get("*/api/v1/brokerage-accounts", () => {
|
||||
requests();
|
||||
return HttpResponse.json([
|
||||
{
|
||||
id: "account-1",
|
||||
name: "Основной",
|
||||
type: "BROKERAGE",
|
||||
openedOn: "2024-08-13",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useAuthenticatedQuery(
|
||||
apiQueryClient.queryOptions("get", "/api/v1/brokerage-accounts"),
|
||||
),
|
||||
{ wrapper: createWrapper() },
|
||||
);
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
expect(requests).not.toHaveBeenCalled();
|
||||
expect(result.current.fetchStatus).toBe("idle");
|
||||
|
||||
configureAuthClient({
|
||||
accessToken: () => "token",
|
||||
refresh: async () => true,
|
||||
clear: vi.fn(),
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true));
|
||||
expect(requests).toHaveBeenCalledOnce();
|
||||
expect(result.current.data).toEqual([
|
||||
{
|
||||
id: "account-1",
|
||||
name: "Основной",
|
||||
type: "BROKERAGE",
|
||||
openedOn: "2024-08-13",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import {
|
||||
type QueryKey,
|
||||
type UseQueryOptions,
|
||||
type UseQueryResult,
|
||||
useQuery,
|
||||
} from "@tanstack/react-query";
|
||||
import { useSyncExternalStore } from "react";
|
||||
import {
|
||||
getAuthenticatedSessionSnapshot,
|
||||
subscribeAuthenticatedSession,
|
||||
} from "./client";
|
||||
|
||||
export function useAuthenticatedQuery<
|
||||
TQueryFnData = unknown,
|
||||
TError = Error,
|
||||
TData = TQueryFnData,
|
||||
TQueryKey extends QueryKey = QueryKey,
|
||||
>(
|
||||
options: UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
|
||||
): UseQueryResult<TData, TError> {
|
||||
const hasSession = useSyncExternalStore(
|
||||
subscribeAuthenticatedSession,
|
||||
getAuthenticatedSessionSnapshot,
|
||||
getAuthenticatedSessionSnapshot,
|
||||
);
|
||||
const enabled = options.enabled;
|
||||
|
||||
return useQuery({
|
||||
...options,
|
||||
enabled: (query) =>
|
||||
hasSession &&
|
||||
(typeof enabled === "function" ? enabled(query) : (enabled ?? true)),
|
||||
});
|
||||
}
|
||||
@@ -12,9 +12,27 @@ type AuthHandlers = {
|
||||
};
|
||||
|
||||
let auth: AuthHandlers | null = null;
|
||||
let hasAuthenticatedSession = false;
|
||||
const authSessionListeners = new Set<() => void>();
|
||||
|
||||
function setAuthenticatedSession(next: boolean) {
|
||||
if (next === hasAuthenticatedSession) return;
|
||||
hasAuthenticatedSession = next;
|
||||
for (const listener of authSessionListeners) listener();
|
||||
}
|
||||
|
||||
export function configureAuthClient(handlers: AuthHandlers | null) {
|
||||
auth = handlers;
|
||||
setAuthenticatedSession(Boolean(auth?.accessToken()));
|
||||
}
|
||||
|
||||
export function getAuthenticatedSessionSnapshot() {
|
||||
return hasAuthenticatedSession;
|
||||
}
|
||||
|
||||
export function subscribeAuthenticatedSession(listener: () => void) {
|
||||
authSessionListeners.add(listener);
|
||||
return () => authSessionListeners.delete(listener);
|
||||
}
|
||||
|
||||
async function authenticatedFetch(request: Request): Promise<Response> {
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
export { useAuthenticatedQuery } from "./authenticated-query";
|
||||
export { apiClient, apiQueryClient, configureAuthClient } from "./client";
|
||||
|
||||
Reference in New Issue
Block a user