Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions packages/base-data-service/src/BaseDataService.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { MOCK_ANY_NAMESPACE, Messenger } from '@metamask/messenger';
import { hashQueryKey } from '@tanstack/query-core';
import { hashKey } from '@tanstack/query-core';
import { BrokenCircuitError } from 'cockatiel';
import { cleanAll } from 'nock';

Expand Down Expand Up @@ -131,7 +131,7 @@ describe('BaseDataService', () => {

const queryKey = ['ExampleDataService:getAssets', MOCK_ASSETS];

const hash = hashQueryKey(queryKey);
const hash = hashKey(queryKey);

expect(publishSpy).toHaveBeenNthCalledWith(
6,
Expand Down Expand Up @@ -186,7 +186,7 @@ describe('BaseDataService', () => {

const queryKey = ['ExampleDataService:getAssets', MOCK_ASSETS];

const hash = hashQueryKey(queryKey);
const hash = hashKey(queryKey);

expect(publishSpy).toHaveBeenNthCalledWith(
8,
Expand Down Expand Up @@ -333,6 +333,7 @@ describe('BaseDataService', () => {
state: {
queries: [
{
dehydratedAt: expect.any(Number),
queryHash:
'["ExampleDataService:getAssets",["eip155:1/slip44:60","bip122:000000000019d6689c085ae165831e93/slip44:0","eip155:1/erc20:0x6b175474e89094c44da98b954eedeac495271d0f"]]',
queryKey: [
Expand Down
93 changes: 71 additions & 22 deletions packages/base-data-service/src/BaseDataService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,16 @@ import type { Json } from '@metamask/utils';
import {
DefaultOptions,
DehydratedState,
FetchInfiniteQueryOptions,
FetchQueryOptions,
GetNextPageParamFunction,
GetPreviousPageParamFunction,
InfiniteData,
InvalidateOptions,
InvalidateQueryFilters,
OmitKeyof,
QueryClient,
QueryClientConfig,
QueryFunction,
WithRequired,
dehydrate,
hydrate,
Expand Down Expand Up @@ -54,7 +56,7 @@ type CacheUpdatedType = DataServiceCacheUpdatedPayload['type'];
export type DataServiceInvalidateQueriesAction<ServiceName extends string> = {
type: `${ServiceName}:invalidateQueries`;
handler: (
filters?: InvalidateQueryFilters<Json>,
filters?: InvalidateQueryFilters,
options?: InvalidateOptions,
) => Promise<void>;
};
Expand Down Expand Up @@ -251,10 +253,14 @@ export class BaseDataService<
options: WithRequired<
OmitKeyof<
FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
'retry' | 'retryDelay'
'retry' | 'retryDelay' | 'queryFn'
>,
'queryKey' | 'queryFn'
>,
'queryKey'
> & {
// Data services always provide a concrete query function; the `skipToken`
// sentinel added in query-core v5 is not supported here.
queryFn: QueryFunction<TQueryFnData, TQueryKey>;
},
): Promise<TData> {
return this.#queryClient.fetchQuery({
...options,
Expand All @@ -280,22 +286,50 @@ export class BaseDataService<
>(
options: WithRequired<
OmitKeyof<
FetchInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
'retry' | 'retryDelay'
FetchQueryOptions<
TQueryFnData,
TError,
InfiniteData<TData, TPageParam>,
TQueryKey,
TPageParam
>,
'retry' | 'retryDelay' | 'queryFn' | 'initialPageParam'
>,
'queryKey' | 'queryFn'
>,
'queryKey'
> & {
// Data services always provide a concrete query function; the `skipToken`
// sentinel added in query-core v5 is not supported here.
queryFn: QueryFunction<TQueryFnData, TQueryKey, TPageParam>;
// These are required by query-core v5 for infinite queries but remain
// optional here: consumers may drive pagination purely by passing an
// explicit `pageParam` (see below).
initialPageParam?: TPageParam;
getNextPageParam?: GetNextPageParamFunction<TPageParam, TQueryFnData>;
getPreviousPageParam?: GetPreviousPageParamFunction<TPageParam, TQueryFnData>;
},
pageParam?: TPageParam,
): Promise<TData> {
const cache = this.#queryClient.getQueryCache();

const query = cache.find<TQueryFnData, TError, InfiniteData<TData>>({
queryKey: options.queryKey,
});
const query = cache.find<TQueryFnData, TError, InfiniteData<TData, TPageParam>>(
{
queryKey: options.queryKey,
},
);

if (!query?.state.data || pageParam === undefined) {
const result = await this.#queryClient.fetchInfiniteQuery({
const result = await this.#queryClient.fetchInfiniteQuery<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
>({
...options,
// query-core v5 requires an `initialPageParam`. When the caller drives
// pagination with an explicit `pageParam`, use it as the initial param
// so the first (and only) page fetched is the requested one.
initialPageParam: (options.initialPageParam ?? pageParam) as TPageParam,
queryFn: (context) =>
this.#policy.execute(() =>
options.queryFn({
Expand All @@ -308,19 +342,34 @@ export class BaseDataService<
return result.pages[0];
}

const { pages } = query.state.data;
const previous = options.getPreviousPageParam?.(pages[0], pages);
const { pages, pageParams } = query.state.data;
const previous = options.getPreviousPageParam?.(
pages[0],
pages,
pageParams[0],
pageParams,
);

const direction = deepEqual(pageParam, previous) ? 'backward' : 'forward';

const result = await query.fetch(undefined, {
meta: {
fetchMore: {
direction,
pageParam,
// query-core v5 no longer accepts an explicit page param via the `fetchMore`
// meta; it derives the next/previous param from these callbacks instead.
// Override them to return exactly the requested page so pagination works
// even when the consumer did not provide page-param callbacks.
const result = await query.fetch(
{
...query.options,
getNextPageParam: () => pageParam,
getPreviousPageParam: () => pageParam,
} as typeof query.options,
{
meta: {
fetchMore: {
direction,
},
},
},
});
);

const pageIndex = result.pageParams.findIndex((param) =>
deepEqual(param, pageParam),
Expand All @@ -337,7 +386,7 @@ export class BaseDataService<
* @returns Nothing.
*/
async invalidateQueries(
filters?: InvalidateQueryFilters<Json>,
filters?: InvalidateQueryFilters,
options?: InvalidateOptions,
): Promise<void> {
return this.#queryClient.invalidateQueries(filters, options);
Expand Down
10 changes: 8 additions & 2 deletions packages/base-data-service/tests/ExampleDataService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,15 +101,21 @@ export class ExampleDataService extends BaseDataService<
return response.json();
},
staleTime: inMilliseconds(1, Duration.Day),
cacheTime: inMilliseconds(1, Duration.Day),
gcTime: inMilliseconds(1, Duration.Day),
});
}

async getActivity(
address: string,
page?: PageParam,
): Promise<GetActivityResponse> {
return this.fetchInfiniteQuery<GetActivityResponse>(
return this.fetchInfiniteQuery<
GetActivityResponse,
unknown,
GetActivityResponse,
[string, string],
PageParam
>(
{
queryKey: [`${this.name}:getActivity`, address],
queryFn: async ({ pageParam }) => {
Expand Down
4 changes: 2 additions & 2 deletions packages/chomp-api-service/src/chomp-api-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,7 @@ export class ChompApiService extends BaseDataService<
* The result is scoped to the authenticated profile and consumers use it
* to decide whether an association already exists, so it is always fetched
* fresh (`staleTime: 0`) and evicted as soon as the call settles
* (`cacheTime: 0`). The query key carries a SHA-256 digest of the bearer
* (`gcTime: 0`). The query key carries a SHA-256 digest of the bearer
* token — the same token the request is made with — so concurrent calls
* only share an in-flight request when they are for the same profile. The
* digest, not the token, is used because query keys leave the service via
Expand All @@ -422,7 +422,7 @@ export class ChompApiService extends BaseDataService<
const jsonResponse = await this.fetchQuery({
queryKey: [`${this.name}:getAssociatedAddresses`, profileKey],
staleTime: 0,
cacheTime: 0,
gcTime: 0,
queryFn: async () => {
const response = await fetch(
new URL('/v1/auth/address', this.#baseUrl),
Expand Down
Loading