fix: stabilize frontend query cache contracts
This commit is contained in:
@@ -42,14 +42,13 @@ export function useBrokerageOperations(
|
|||||||
) {
|
) {
|
||||||
const params = brokerageOperationsQueryParams(query);
|
const params = brokerageOperationsQueryParams(query);
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: ["brokerage-operations", accountId ?? "", params] as const,
|
|
||||||
enabled: Boolean(accountId && accessToken),
|
|
||||||
staleTime: 30_000,
|
|
||||||
retry: false,
|
|
||||||
...apiQueryClient.queryOptions(
|
...apiQueryClient.queryOptions(
|
||||||
"get",
|
"get",
|
||||||
"/api/v1/brokerage-accounts/{accountId}/operations",
|
"/api/v1/brokerage-accounts/{accountId}/operations",
|
||||||
{ params: { path: { accountId: accountId ?? "" }, query: params } },
|
{ params: { path: { accountId: accountId ?? "" }, query: params } },
|
||||||
),
|
),
|
||||||
|
enabled: Boolean(accountId && accessToken),
|
||||||
|
staleTime: 30_000,
|
||||||
|
retry: false,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,17 +2,20 @@ import { useQuery } from "@tanstack/react-query";
|
|||||||
import { apiQueryClient } from "@/shared/api";
|
import { apiQueryClient } from "@/shared/api";
|
||||||
import type { paths } from "@/shared/api/generated/schema";
|
import type { paths } from "@/shared/api/generated/schema";
|
||||||
|
|
||||||
export const brokerageAccountsQueryKey = ["brokerage-accounts"] as const;
|
const brokerageAccountsQueryOptions = () =>
|
||||||
|
apiQueryClient.queryOptions("get", "/api/v1/brokerage-accounts");
|
||||||
|
|
||||||
|
export const brokerageAccountsQueryKey =
|
||||||
|
brokerageAccountsQueryOptions().queryKey;
|
||||||
|
|
||||||
export type BrokerageAccount =
|
export type BrokerageAccount =
|
||||||
paths["/api/v1/brokerage-accounts"]["get"]["responses"][200]["content"]["application/json"][number];
|
paths["/api/v1/brokerage-accounts"]["get"]["responses"][200]["content"]["application/json"][number];
|
||||||
|
|
||||||
export function useBrokerageAccounts(accessToken: string | null) {
|
export function useBrokerageAccounts(accessToken: string | null) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: brokerageAccountsQueryKey,
|
...brokerageAccountsQueryOptions(),
|
||||||
enabled: Boolean(accessToken),
|
enabled: Boolean(accessToken),
|
||||||
staleTime: 60_000,
|
staleTime: 60_000,
|
||||||
retry: false,
|
retry: false,
|
||||||
...apiQueryClient.queryOptions("get", "/api/v1/brokerage-accounts"),
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,14 +12,13 @@ export function useBrokerageEvents(
|
|||||||
accessToken: string | null,
|
accessToken: string | null,
|
||||||
) {
|
) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: ["brokerage-events", accountId ?? ""] as const,
|
|
||||||
enabled: Boolean(accountId && accessToken),
|
|
||||||
staleTime: 30_000,
|
|
||||||
retry: false,
|
|
||||||
...apiQueryClient.queryOptions(
|
...apiQueryClient.queryOptions(
|
||||||
"get",
|
"get",
|
||||||
"/api/v1/brokerage-accounts/{accountId}/events",
|
"/api/v1/brokerage-accounts/{accountId}/events",
|
||||||
{ params: { path: { accountId: accountId ?? "" } } },
|
{ params: { path: { accountId: accountId ?? "" } } },
|
||||||
),
|
),
|
||||||
|
enabled: Boolean(accountId && accessToken),
|
||||||
|
staleTime: 30_000,
|
||||||
|
retry: false,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,9 +2,6 @@ import { useQuery } from "@tanstack/react-query";
|
|||||||
import { apiQueryClient } from "@/shared/api";
|
import { apiQueryClient } from "@/shared/api";
|
||||||
import type { paths } from "@/shared/api/generated/schema";
|
import type { paths } from "@/shared/api/generated/schema";
|
||||||
|
|
||||||
const portfolioQueryKey = (accountId: string) =>
|
|
||||||
["portfolio", accountId] as const;
|
|
||||||
|
|
||||||
const portfolioQueryPolicy = {
|
const portfolioQueryPolicy = {
|
||||||
staleTime: 30_000,
|
staleTime: 30_000,
|
||||||
retry: false,
|
retry: false,
|
||||||
@@ -18,13 +15,12 @@ export function usePortfolio(
|
|||||||
accessToken: string | null,
|
accessToken: string | null,
|
||||||
) {
|
) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: portfolioQueryKey(accountId ?? ""),
|
|
||||||
enabled: Boolean(accountId && accessToken),
|
|
||||||
...portfolioQueryPolicy,
|
|
||||||
...apiQueryClient.queryOptions(
|
...apiQueryClient.queryOptions(
|
||||||
"get",
|
"get",
|
||||||
"/api/v1/brokerage-accounts/{accountId}/portfolio",
|
"/api/v1/brokerage-accounts/{accountId}/portfolio",
|
||||||
{ params: { path: { accountId: accountId ?? "" } } },
|
{ params: { path: { accountId: accountId ?? "" } } },
|
||||||
),
|
),
|
||||||
|
enabled: Boolean(accountId && accessToken),
|
||||||
|
...portfolioQueryPolicy,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,99 @@
|
|||||||
|
import { MantineProvider } from "@mantine/core";
|
||||||
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||||
|
import {
|
||||||
|
cleanup,
|
||||||
|
fireEvent,
|
||||||
|
render,
|
||||||
|
screen,
|
||||||
|
waitFor,
|
||||||
|
} from "@testing-library/react";
|
||||||
|
import { HttpResponse, http } from "msw";
|
||||||
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import { apiQueryClient } from "@/shared/api";
|
||||||
|
import { server } from "@/test/server";
|
||||||
|
import { TbankConnectionSection } from "./TbankConnectionSection";
|
||||||
|
|
||||||
|
vi.mock("@/features/auth", () => ({
|
||||||
|
useAuth: () => ({ accessToken: "test-token" }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
afterEach(cleanup);
|
||||||
|
|
||||||
|
const brokerageAccountsQueryKey = apiQueryClient.queryOptions(
|
||||||
|
"get",
|
||||||
|
"/api/v1/brokerage-accounts",
|
||||||
|
).queryKey;
|
||||||
|
|
||||||
|
function renderSection(client: QueryClient) {
|
||||||
|
return render(
|
||||||
|
<MantineProvider>
|
||||||
|
<QueryClientProvider client={client}>
|
||||||
|
<TbankConnectionSection />
|
||||||
|
</QueryClientProvider>
|
||||||
|
</MantineProvider>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function seededClient() {
|
||||||
|
const client = new QueryClient({
|
||||||
|
defaultOptions: { queries: { retry: false } },
|
||||||
|
});
|
||||||
|
client.setQueryData(brokerageAccountsQueryKey, [
|
||||||
|
{
|
||||||
|
id: "account-1",
|
||||||
|
name: "Основной счет",
|
||||||
|
type: "BROKERAGE",
|
||||||
|
openedOn: null,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
return client;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("TbankConnectionSection", () => {
|
||||||
|
it("updates the generated status cache and invalidates accounts after connecting", async () => {
|
||||||
|
const client = seededClient();
|
||||||
|
renderSection(client);
|
||||||
|
|
||||||
|
await screen.findByText("Не подключено");
|
||||||
|
fireEvent.change(screen.getByLabelText("Token T-Bank"), {
|
||||||
|
target: { value: "replacement-token" },
|
||||||
|
});
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Подключить" }));
|
||||||
|
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(
|
||||||
|
screen.getByRole("button", { name: "Заменить token" }),
|
||||||
|
).toBeInTheDocument(),
|
||||||
|
);
|
||||||
|
expect(client.getQueryState(brokerageAccountsQueryKey)?.isInvalidated).toBe(
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("updates the generated status cache and invalidates accounts after deleting", async () => {
|
||||||
|
server.use(
|
||||||
|
http.get("*/api/v1/tbank-connection", () =>
|
||||||
|
HttpResponse.json({
|
||||||
|
connected: true,
|
||||||
|
connectedAt: "2026-08-14T00:00:00Z",
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const client = seededClient();
|
||||||
|
renderSection(client);
|
||||||
|
|
||||||
|
fireEvent.click(
|
||||||
|
await screen.findByRole("button", { name: "Удалить подключение" }),
|
||||||
|
);
|
||||||
|
fireEvent.click(await screen.findByRole("button", { name: /^Удалить$/ }));
|
||||||
|
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(
|
||||||
|
screen.getByRole("button", { name: "Подключить" }),
|
||||||
|
).toBeInTheDocument(),
|
||||||
|
);
|
||||||
|
expect(client.getQueryState(brokerageAccountsQueryKey)?.isInvalidated).toBe(
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -17,7 +17,10 @@ import {
|
|||||||
TbankConnectionError,
|
TbankConnectionError,
|
||||||
TbankConnectionLoading,
|
TbankConnectionLoading,
|
||||||
} from "./TbankConnectionSection.view";
|
} from "./TbankConnectionSection.view";
|
||||||
import { useTbankConnectionViewModel } from "./TbankConnectionSection.vm";
|
import {
|
||||||
|
tbankConnectionQueryKey,
|
||||||
|
useTbankConnectionViewModel,
|
||||||
|
} from "./TbankConnectionSection.vm";
|
||||||
|
|
||||||
type Status =
|
type Status =
|
||||||
paths["/api/v1/tbank-connection"]["get"]["responses"][200]["content"]["application/json"];
|
paths["/api/v1/tbank-connection"]["get"]["responses"][200]["content"]["application/json"];
|
||||||
@@ -49,18 +52,18 @@ function TbankConnectionSectionLoaded({ status }: { status: Status }) {
|
|||||||
} = useForm<{ token: string }>();
|
} = useForm<{ token: string }>();
|
||||||
const update = apiQueryClient.useMutation("put", "/api/v1/tbank-connection", {
|
const update = apiQueryClient.useMutation("put", "/api/v1/tbank-connection", {
|
||||||
onSuccess: (data) => {
|
onSuccess: (data) => {
|
||||||
queryClient.setQueryData(["tbank-connection"], data);
|
queryClient.setQueryData(tbankConnectionQueryKey, data);
|
||||||
queryClient.invalidateQueries({ queryKey: brokerageAccountsQueryKey });
|
queryClient.invalidateQueries({ queryKey: brokerageAccountsQueryKey });
|
||||||
reset();
|
reset();
|
||||||
},
|
},
|
||||||
onError: (error) => setRequestError(errorCode(error)),
|
onError: (error) => setRequestError(errorCode(error) ?? "REQUEST_ERROR"),
|
||||||
});
|
});
|
||||||
const remove = apiQueryClient.useMutation(
|
const remove = apiQueryClient.useMutation(
|
||||||
"delete",
|
"delete",
|
||||||
"/api/v1/tbank-connection",
|
"/api/v1/tbank-connection",
|
||||||
{
|
{
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.setQueryData<Status>(["tbank-connection"], {
|
queryClient.setQueryData<Status>(tbankConnectionQueryKey, {
|
||||||
connected: false,
|
connected: false,
|
||||||
connectedAt: null,
|
connectedAt: null,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,12 +2,16 @@ import { useQuery } from "@tanstack/react-query";
|
|||||||
import { useAuth } from "@/features/auth";
|
import { useAuth } from "@/features/auth";
|
||||||
import { apiQueryClient } from "@/shared/api";
|
import { apiQueryClient } from "@/shared/api";
|
||||||
|
|
||||||
|
const tbankConnectionQueryOptions = () =>
|
||||||
|
apiQueryClient.queryOptions("get", "/api/v1/tbank-connection");
|
||||||
|
|
||||||
|
export const tbankConnectionQueryKey = tbankConnectionQueryOptions().queryKey;
|
||||||
|
|
||||||
export function useTbankConnectionViewModel() {
|
export function useTbankConnectionViewModel() {
|
||||||
const { accessToken } = useAuth();
|
const { accessToken } = useAuth();
|
||||||
const status = useQuery({
|
const status = useQuery({
|
||||||
queryKey: ["tbank-connection"],
|
...tbankConnectionQueryOptions(),
|
||||||
enabled: Boolean(accessToken),
|
enabled: Boolean(accessToken),
|
||||||
...apiQueryClient.queryOptions("get", "/api/v1/tbank-connection"),
|
|
||||||
});
|
});
|
||||||
if (status.isPending) return { state: "loading" as const };
|
if (status.isPending) return { state: "loading" as const };
|
||||||
if (status.isError)
|
if (status.isError)
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ export function AccountEventsPage() {
|
|||||||
if (events.isLoading) return <AccountEventsPageLoading />;
|
if (events.isLoading) return <AccountEventsPageLoading />;
|
||||||
if (events.isError)
|
if (events.isError)
|
||||||
return <AccountEventsPageError retry={() => events.refetch()} />;
|
return <AccountEventsPageError retry={() => events.refetch()} />;
|
||||||
|
if (!events.data) return <AccountEventsPageLoading />;
|
||||||
if (!events.data.events.length) return <AccountEventsPageEmpty />;
|
if (!events.data.events.length) return <AccountEventsPageEmpty />;
|
||||||
return <AccountEventsPageLoaded events={events.data.events} />;
|
return <AccountEventsPageLoaded events={events.data.events} />;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -68,6 +68,16 @@ export function AccountOperationsPage() {
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
if (!operations.data)
|
||||||
|
return (
|
||||||
|
<StateView
|
||||||
|
loading
|
||||||
|
title={t("states.loadingTitle")}
|
||||||
|
text={t("states.loadingText")}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
const { data } = operations;
|
||||||
|
const nextCursor = data.nextCursor;
|
||||||
return (
|
return (
|
||||||
<Stack maw={960} gap="lg">
|
<Stack maw={960} gap="lg">
|
||||||
<Title order={1}>{t("ledger.title")}</Title>
|
<Title order={1}>{t("ledger.title")}</Title>
|
||||||
@@ -109,8 +119,8 @@ export function AccountOperationsPage() {
|
|||||||
))}
|
))}
|
||||||
</Group>
|
</Group>
|
||||||
</Checkbox.Group>
|
</Checkbox.Group>
|
||||||
{operations.data.items.length ? (
|
{data.items.length ? (
|
||||||
operations.data.items.map((operation) => (
|
data.items.map((operation) => (
|
||||||
<OperationRow key={operation.id} operation={operation} />
|
<OperationRow key={operation.id} operation={operation} />
|
||||||
))
|
))
|
||||||
) : (
|
) : (
|
||||||
@@ -119,7 +129,7 @@ export function AccountOperationsPage() {
|
|||||||
text={t("ledger.emptyText")}
|
text={t("ledger.emptyText")}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{operations.data.hasNext || cursors.length ? (
|
{data.hasNext || cursors.length ? (
|
||||||
<Group justify="space-between">
|
<Group justify="space-between">
|
||||||
<Button
|
<Button
|
||||||
disabled={!cursors.length}
|
disabled={!cursors.length}
|
||||||
@@ -128,11 +138,10 @@ export function AccountOperationsPage() {
|
|||||||
{t("ledger.previous")}
|
{t("ledger.previous")}
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
disabled={!operations.data.hasNext || !operations.data.nextCursor}
|
disabled={!data.hasNext || !nextCursor}
|
||||||
onClick={() =>
|
onClick={() => {
|
||||||
operations.data.nextCursor &&
|
if (nextCursor) setCursors((value) => [...value, nextCursor]);
|
||||||
setCursors((value) => [...value, operations.data.nextCursor])
|
}}
|
||||||
}
|
|
||||||
>
|
>
|
||||||
{t("ledger.next")}
|
{t("ledger.next")}
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -1,17 +1,18 @@
|
|||||||
import { useQueryClient } from "@tanstack/react-query";
|
import { useQueryClient } from "@tanstack/react-query";
|
||||||
import { useParams } from "react-router";
|
import { useParams } from "react-router";
|
||||||
import type { BrokerageAccount } from "@/entities/brokerage-account";
|
import {
|
||||||
|
type BrokerageAccount,
|
||||||
|
brokerageAccountsQueryKey,
|
||||||
|
} from "@/entities/brokerage-account";
|
||||||
import { portfolioErrorCode, usePortfolio } from "@/entities/portfolio";
|
import { portfolioErrorCode, usePortfolio } from "@/entities/portfolio";
|
||||||
import { useAuth } from "@/features/auth";
|
import { useAuth } from "@/features/auth";
|
||||||
|
|
||||||
const accountsQueryKey = ["brokerage-accounts"] as const;
|
|
||||||
|
|
||||||
export function useAccountPageViewModel() {
|
export function useAccountPageViewModel() {
|
||||||
const { accountId } = useParams();
|
const { accountId } = useParams();
|
||||||
const { accessToken } = useAuth();
|
const { accessToken } = useAuth();
|
||||||
const portfolio = usePortfolio(accountId, accessToken);
|
const portfolio = usePortfolio(accountId, accessToken);
|
||||||
const account = useQueryClient()
|
const account = useQueryClient()
|
||||||
.getQueryData<BrokerageAccount[]>(accountsQueryKey)
|
.getQueryData<BrokerageAccount[]>(brokerageAccountsQueryKey)
|
||||||
?.find((item) => item.id === accountId);
|
?.find((item) => item.id === accountId);
|
||||||
if (portfolio.isError)
|
if (portfolio.isError)
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -9,6 +9,7 @@
|
|||||||
"types": ["vite/client"],
|
"types": ["vite/client"],
|
||||||
"allowArbitraryExtensions": true,
|
"allowArbitraryExtensions": true,
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
|
"strict": true,
|
||||||
|
|
||||||
/* Bundler mode */
|
/* Bundler mode */
|
||||||
"moduleResolution": "bundler",
|
"moduleResolution": "bundler",
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
"lib": ["ES2023"],
|
"lib": ["ES2023"],
|
||||||
"types": ["node"],
|
"types": ["node"],
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
|
"strict": true,
|
||||||
|
|
||||||
/* Bundler mode */
|
/* Bundler mode */
|
||||||
"module": "nodenext",
|
"module": "nodenext",
|
||||||
|
|||||||
Reference in New Issue
Block a user