From 994542ba4056b778e3d7abade5ec3d726b3691d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjam=C3=ADn=20Vicente?= Date: Thu, 26 Nov 2026 00:02:37 -0300 Subject: [PATCH 1/2] feat(query-core): add framework-agnostic options helpers --- .changeset/core-query-options.md | 5 + docs/framework/react/guides/query-options.md | 2 + .../infinite-query-options.test-d.ts | 31 ++- .../src/__tests__/inject-queries.test-d.ts | 42 ++++ .../src/__tests__/mutation-options.test-d.ts | 20 +- .../src/__tests__/query-options.test-d.ts | 13 + .../createMutationController.test-d.ts | 20 +- .../__tests__/createQueryController.test-d.ts | 21 +- .../__tests__/infiniteQueryOptions.test-d.ts | 33 +++ .../__tests__/infiniteQueryOptions.test-d.tsx | 45 +++- .../src/__tests__/mutationOptions.test-d.tsx | 17 +- .../src/__tests__/queryOptions.test-d.tsx | 30 ++- .../__tests__/infiniteQueryOptions.test-d.tsx | 220 +++++++++++++++++ .../__tests__/infiniteQueryOptions.test.ts | 21 ++ .../src/__tests__/mutationOptions.test-d.tsx | 91 +++++++ .../src/__tests__/mutationOptions.test.ts | 17 ++ .../src/__tests__/queryOptions.test-d.tsx | 183 ++++++++++++++ .../src/__tests__/queryOptions.test.ts | 17 ++ packages/query-core/src/index.ts | 6 + .../query-core/src/infiniteQueryOptions.ts | 227 ++++++++++++++++++ packages/query-core/src/mutationOptions.ts | 94 ++++++++ packages/query-core/src/queryOptions.ts | 177 ++++++++++++++ .../__tests__/infiniteQueryOptions.test-d.tsx | 45 +++- .../src/__tests__/mutationOptions.test-d.tsx | 17 +- .../src/__tests__/queryOptions.test-d.tsx | 30 ++- .../__tests__/infiniteQueryOptions.test-d.tsx | 31 ++- .../src/__tests__/mutationOptions.test-d.tsx | 17 +- .../src/__tests__/queryOptions.test-d.tsx | 13 + .../tests/createQuery/createQuery.test-d.ts | 13 + .../tests/infiniteQueryOptions.test-d.ts | 30 ++- .../mutationOptions/mutationOptions.test-d.ts | 17 +- 31 files changed, 1531 insertions(+), 14 deletions(-) create mode 100644 .changeset/core-query-options.md create mode 100644 packages/query-core/src/__tests__/infiniteQueryOptions.test-d.tsx create mode 100644 packages/query-core/src/__tests__/infiniteQueryOptions.test.ts create mode 100644 packages/query-core/src/__tests__/mutationOptions.test-d.tsx create mode 100644 packages/query-core/src/__tests__/mutationOptions.test.ts create mode 100644 packages/query-core/src/__tests__/queryOptions.test-d.tsx create mode 100644 packages/query-core/src/__tests__/queryOptions.test.ts create mode 100644 packages/query-core/src/infiniteQueryOptions.ts create mode 100644 packages/query-core/src/mutationOptions.ts create mode 100644 packages/query-core/src/queryOptions.ts diff --git a/.changeset/core-query-options.md b/.changeset/core-query-options.md new file mode 100644 index 00000000000..17a0fb90000 --- /dev/null +++ b/.changeset/core-query-options.md @@ -0,0 +1,5 @@ +--- +'@tanstack/query-core': minor +--- + +Add framework-agnostic `queryOptions`, `infiniteQueryOptions`, and `mutationOptions` helpers. They only accept options that every adapter supports, so framework-specific options such as `throwOnError`, `suspense`, and `notifyOnChangeProps` stay in each adapter's helpers. diff --git a/docs/framework/react/guides/query-options.md b/docs/framework/react/guides/query-options.md index da265975144..9cdcd86c67e 100644 --- a/docs/framework/react/guides/query-options.md +++ b/docs/framework/react/guides/query-options.md @@ -5,6 +5,8 @@ title: Query Options One of the best ways to share `queryKey` and `queryFn` between multiple places, yet keep them co-located to one another, is to use the `queryOptions` helper. At runtime, this helper just returns whatever you pass into it, but it has a lot of advantages when using it [with TypeScript](../typescript.md#typing-query-options). You can define all possible options for a query in one place, and you'll also get type inference and type safety for all of them. +For framework-agnostic code, `@tanstack/query-core` also exports `queryOptions`, `infiniteQueryOptions`, and `mutationOptions`. They infer query data, page parameters, and mutation variables without depending on a framework, but they only accept the options that every adapter supports. Use the adapter's helpers when you need framework-specific options such as `throwOnError`. + [//]: # 'Example1' ```ts diff --git a/packages/angular-query/src/__tests__/infinite-query-options.test-d.ts b/packages/angular-query/src/__tests__/infinite-query-options.test-d.ts index 8df6eaf308e..d3059710020 100644 --- a/packages/angular-query/src/__tests__/infinite-query-options.test-d.ts +++ b/packages/angular-query/src/__tests__/infinite-query-options.test-d.ts @@ -1,4 +1,9 @@ -import { QueryClient, dataTagSymbol, skipToken } from '@tanstack/query-core' +import { + QueryClient, + infiniteQueryOptions as coreInfiniteQueryOptions, + dataTagSymbol, + skipToken, +} from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' import { assertType, describe, expectTypeOf, it } from 'vitest' import { defaultQueryFn } from '..' @@ -22,6 +27,30 @@ export const exportedInfiniteQueryOptions = infiniteQueryOptions({ }) describe('infiniteQueryOptions', () => { + it('should infer data from core infiniteQueryOptions', () => { + const options = coreInfiniteQueryOptions({ + queryKey: createKey(), + initialPageParam: 0, + queryFn: ({ pageParam }) => Promise.resolve(pageParam), + getNextPageParam: () => undefined, + }) + const query = injectInfiniteQuery(() => options) + expectTypeOf(query.data()).toEqualTypeOf | undefined>() + }) + + it('should preserve selected data and initialData from core infiniteQueryOptions', () => { + const options = coreInfiniteQueryOptions({ + queryKey: createKey(), + initialPageParam: 0, + queryFn: ({ pageParam }) => Promise.resolve(pageParam), + getNextPageParam: () => undefined, + initialData: { pages: [1], pageParams: [0] }, + select: (data) => data.pages.length, + }) + const query = injectInfiniteQuery(() => options) + expectTypeOf(query.data()).toEqualTypeOf() + }) + it('should not allow excess properties', () => { const key = createKey() assertType( diff --git a/packages/angular-query/src/__tests__/inject-queries.test-d.ts b/packages/angular-query/src/__tests__/inject-queries.test-d.ts index e92158a8df0..bf5171ac423 100644 --- a/packages/angular-query/src/__tests__/inject-queries.test-d.ts +++ b/packages/angular-query/src/__tests__/inject-queries.test-d.ts @@ -1,4 +1,5 @@ import { computed } from '@angular/core' +import { queryOptions as coreQueryOptions } from '@tanstack/query-core' import { describe, expectTypeOf, it } from 'vitest' import { injectQueries, skipToken, toResource } from '..' import { queryOptions } from '../query-options' @@ -6,6 +7,47 @@ import type { Resource, Signal } from '@angular/core' import type { CreateQueryOptions, CreateQueryResult, OmitKeyof } from '..' describe('InjectQueries config object overload', () => { + it('should infer tuple data and initialData from core queryOptions', () => { + const numberOptions = coreQueryOptions({ + queryKey: ['number'], + queryFn: () => Promise.resolve(1), + }) + const stringOptions = coreQueryOptions({ + queryKey: ['string'], + queryFn: () => Promise.resolve('one'), + initialData: 'initial', + }) + const results = injectQueries(() => ({ + queries: [numberOptions, stringOptions], + })) + + expectTypeOf(results()[0].data()).toEqualTypeOf() + expectTypeOf(results()[1].data()).toEqualTypeOf() + }) + + it('should infer selected data and custom errors from core queryOptions in combine', () => { + class CustomError extends Error { + detail = 'detail' + } + const options = coreQueryOptions({ + queryKey: ['selected'], + queryFn: () => Promise.resolve(1), + select: (data) => data.toString(), + }) + const results = injectQueries(() => ({ queries: [options] })) + expectTypeOf(results()[0].data()).toEqualTypeOf() + expectTypeOf(results()[0].error()).toEqualTypeOf() + + const combined = injectQueries(() => ({ + queries: [options], + combine: ([result]) => ({ data: result.data, error: result.error }), + })) + expectTypeOf(combined()).toEqualTypeOf<{ + data: string | undefined + error: CustomError | null + }>() + }) + it('keeps optional initial data in service queryOptions results undefined-capable', () => { const service = { options: () => queryOptions({ queryKey: ['service'], queryFn: () => 1 }), diff --git a/packages/angular-query/src/__tests__/mutation-options.test-d.ts b/packages/angular-query/src/__tests__/mutation-options.test-d.ts index 1243ca8ec48..e947b2703d6 100644 --- a/packages/angular-query/src/__tests__/mutation-options.test-d.ts +++ b/packages/angular-query/src/__tests__/mutation-options.test-d.ts @@ -1,4 +1,7 @@ -import { QueryClient } from '@tanstack/query-core' +import { + QueryClient, + mutationOptions as coreMutationOptions, +} from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' import { assertType, describe, expectTypeOf, it } from 'vitest' import { @@ -7,6 +10,7 @@ import { injectMutationState, mutationOptions, } from '..' +import type { Signal } from '@angular/core' import type { DefaultError, MutationFunctionContext, @@ -174,6 +178,20 @@ describe('mutationOptions', () => { ) }) + it('should infer types when core mutationOptions are used with injectMutation', () => { + const mutation = injectMutation(() => + coreMutationOptions({ + mutationFn: (input: { id: string }) => Promise.resolve(input.id), + }), + ) + + expectTypeOf(mutation.data).toEqualTypeOf>() + expectTypeOf(mutation.variables).toEqualTypeOf< + Signal<{ id: string } | undefined> + >() + expectTypeOf(mutation.mutate).toBeCallableWith({ id: '1' }) + }) + it('should infer types when used with injectIsMutating', () => { const key = createKey() const isMutating = injectIsMutating(() => diff --git a/packages/angular-query/src/__tests__/query-options.test-d.ts b/packages/angular-query/src/__tests__/query-options.test-d.ts index b9d2d9ee713..36e077a8ce0 100644 --- a/packages/angular-query/src/__tests__/query-options.test-d.ts +++ b/packages/angular-query/src/__tests__/query-options.test-d.ts @@ -1,3 +1,4 @@ +import { queryOptions as coreQueryOptions } from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' import { assertType, describe, expectTypeOf, it } from 'vitest' import { @@ -20,6 +21,18 @@ export const exportedQueryOptions = queryOptions({ }) describe('queryOptions', () => { + it('should work when core queryOptions are passed to injectQuery', () => { + const options = coreQueryOptions({ + queryKey: createKey(), + queryFn: () => Promise.resolve({ id: '1', title: 'Do Laundry' }), + }) + + const { data } = injectQuery(() => options) + expectTypeOf(data).toEqualTypeOf< + Signal<{ id: string; title: string } | undefined> + >() + }) + it('should not allow excess properties', () => { expectTypeOf(queryOptions).parameter(0).not.toHaveProperty('stallTime') }) diff --git a/packages/lit-query/src/__tests__/createMutationController.test-d.ts b/packages/lit-query/src/__tests__/createMutationController.test-d.ts index 3628753186d..77535a6f673 100644 --- a/packages/lit-query/src/__tests__/createMutationController.test-d.ts +++ b/packages/lit-query/src/__tests__/createMutationController.test-d.ts @@ -1,4 +1,7 @@ -import { QueryClient } from '@tanstack/query-core' +import { + QueryClient, + mutationOptions as coreMutationOptions, +} from '@tanstack/query-core' import { LitElement } from 'lit' import { describe, expectTypeOf, it } from 'vitest' import { createMutationController } from '../createMutationController.js' @@ -12,6 +15,21 @@ import type { MutationResultAccessor } from '../createMutationController.js' class Host extends LitElement {} describe('createMutationController', () => { + it('should infer types from core mutationOptions', () => { + const mutation = createMutationController( + new Host(), + () => + coreMutationOptions({ + mutationFn: async (input: { id: string }) => input.id, + }), + new QueryClient(), + ) + expectTypeOf(mutation().data).toEqualTypeOf() + expectTypeOf(mutation().variables).toEqualTypeOf< + { id: string } | undefined + >() + }) + it('should infer TData from mutationFn return type', () => { const mutation = createMutationController( new Host(), diff --git a/packages/lit-query/src/__tests__/createQueryController.test-d.ts b/packages/lit-query/src/__tests__/createQueryController.test-d.ts index 683c09c9965..ad68e04a22c 100644 --- a/packages/lit-query/src/__tests__/createQueryController.test-d.ts +++ b/packages/lit-query/src/__tests__/createQueryController.test-d.ts @@ -1,4 +1,7 @@ -import { QueryClient } from '@tanstack/query-core' +import { + QueryClient, + queryOptions as coreQueryOptions, +} from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' import { LitElement } from 'lit' import { assertType, describe, expectTypeOf, it } from 'vitest' @@ -15,6 +18,22 @@ import type { CreateQueryOptions } from '../createQueryController.js' class Host extends LitElement {} describe('createQueryController', () => { + it('should infer data from core queryOptions', () => { + const query = createQueryController( + new Host(), + () => + coreQueryOptions({ + queryKey: createKey(), + queryFn: () => Promise.resolve({ id: '1', title: 'Do Laundry' }), + }), + new QueryClient(), + ) + + expectTypeOf(query().data).toEqualTypeOf< + { id: string; title: string } | undefined + >() + }) + it('should default data to unknown when the query function is not specified', () => { const query = createQueryController( new Host(), diff --git a/packages/lit-query/src/__tests__/infiniteQueryOptions.test-d.ts b/packages/lit-query/src/__tests__/infiniteQueryOptions.test-d.ts index e3bbe016eb4..893330ae32a 100644 --- a/packages/lit-query/src/__tests__/infiniteQueryOptions.test-d.ts +++ b/packages/lit-query/src/__tests__/infiniteQueryOptions.test-d.ts @@ -1,5 +1,6 @@ import { QueryClient, + infiniteQueryOptions as coreInfiniteQueryOptions, dataTagErrorSymbol, dataTagSymbol, skipToken, @@ -18,6 +19,38 @@ import type { class Host extends LitElement {} describe('infiniteQueryOptions', () => { + it('should infer data from core infiniteQueryOptions', () => { + const options = coreInfiniteQueryOptions({ + queryKey: createKey(), + initialPageParam: 0, + queryFn: ({ pageParam }) => Promise.resolve(pageParam), + getNextPageParam: () => undefined, + }) + const query = createInfiniteQueryController( + new Host(), + () => options, + new QueryClient(), + ) + expectTypeOf(query().data).toEqualTypeOf | undefined>() + }) + + it('should preserve selected data and initialData from core infiniteQueryOptions', () => { + const options = coreInfiniteQueryOptions({ + queryKey: createKey(), + initialPageParam: 0, + queryFn: ({ pageParam }) => Promise.resolve(pageParam), + getNextPageParam: () => undefined, + initialData: { pages: [1], pageParams: [0] }, + select: (data) => data.pages.length, + }) + const query = createInfiniteQueryController( + new Host(), + () => options, + new QueryClient(), + ) + expectTypeOf(query().data).toEqualTypeOf() + }) + it('should not allow excess properties', () => { assertType( infiniteQueryOptions({ diff --git a/packages/preact-query/src/__tests__/infiniteQueryOptions.test-d.tsx b/packages/preact-query/src/__tests__/infiniteQueryOptions.test-d.tsx index db5b7c6aa23..b92bac779ca 100644 --- a/packages/preact-query/src/__tests__/infiniteQueryOptions.test-d.tsx +++ b/packages/preact-query/src/__tests__/infiniteQueryOptions.test-d.tsx @@ -1,4 +1,9 @@ -import { QueryClient, dataTagSymbol, skipToken } from '@tanstack/query-core' +import { + QueryClient, + infiniteQueryOptions as coreInfiniteQueryOptions, + dataTagSymbol, + skipToken, +} from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' import { assertType, describe, expectTypeOf, it } from 'vitest' import { defaultQueryFn } from '..' @@ -23,6 +28,44 @@ export const exportedInfiniteQueryOptions = infiniteQueryOptions({ }) describe('infiniteQueryOptions', () => { + it('should accept core options with optional initialData in suspense', () => { + const options = coreInfiniteQueryOptions({ + queryKey: createKey(), + initialPageParam: 0, + queryFn: ({ pageParam }) => Promise.resolve(pageParam), + getNextPageParam: () => undefined, + initialData: + Math.random() > 0.5 ? { pages: [1], pageParams: [0] } : undefined, + }) + expectTypeOf(useSuspenseInfiniteQuery(options).data).toEqualTypeOf< + InfiniteData + >() + }) + + it('should infer data from core infiniteQueryOptions', () => { + const options = coreInfiniteQueryOptions({ + queryKey: createKey(), + initialPageParam: 0, + queryFn: ({ pageParam }) => Promise.resolve(pageParam), + getNextPageParam: () => undefined, + }) + const query = useInfiniteQuery(options) + expectTypeOf(query.data).toEqualTypeOf | undefined>() + }) + + it('should preserve selected data and initialData from core infiniteQueryOptions', () => { + const options = coreInfiniteQueryOptions({ + queryKey: createKey(), + initialPageParam: 0, + queryFn: ({ pageParam }) => Promise.resolve(pageParam), + getNextPageParam: () => undefined, + initialData: { pages: [1], pageParams: [0] }, + select: (data) => data.pages.length, + }) + const query = useInfiniteQuery(options) + expectTypeOf(query.data).toEqualTypeOf() + }) + it('should not allow excess properties', () => { assertType( infiniteQueryOptions({ diff --git a/packages/preact-query/src/__tests__/mutationOptions.test-d.tsx b/packages/preact-query/src/__tests__/mutationOptions.test-d.tsx index 8085b19433d..fb3060b8f0a 100644 --- a/packages/preact-query/src/__tests__/mutationOptions.test-d.tsx +++ b/packages/preact-query/src/__tests__/mutationOptions.test-d.tsx @@ -1,4 +1,7 @@ -import { QueryClient } from '@tanstack/query-core' +import { + QueryClient, + mutationOptions as coreMutationOptions, +} from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' import { assertType, describe, expectTypeOf, it } from 'vitest' import { useIsMutating, useMutation, useMutationState } from '..' @@ -161,6 +164,18 @@ describe('mutationOptions', () => { ) }) + it('should infer types when core mutationOptions are used with useMutation', () => { + const mutation = useMutation( + coreMutationOptions({ + mutationFn: (input: { id: string }) => Promise.resolve(input.id), + }), + ) + + expectTypeOf(mutation.data).toEqualTypeOf() + expectTypeOf(mutation.variables).toEqualTypeOf<{ id: string } | undefined>() + expectTypeOf(mutation.mutate).toBeCallableWith({ id: '1' }) + }) + it('should infer types when used with useIsMutating', () => { const isMutating = useIsMutating( mutationOptions({ diff --git a/packages/preact-query/src/__tests__/queryOptions.test-d.tsx b/packages/preact-query/src/__tests__/queryOptions.test-d.tsx index a4f8dce8301..d691ca838b3 100644 --- a/packages/preact-query/src/__tests__/queryOptions.test-d.tsx +++ b/packages/preact-query/src/__tests__/queryOptions.test-d.tsx @@ -1,4 +1,9 @@ -import { QueryClient, dataTagSymbol, skipToken } from '@tanstack/query-core' +import { + QueryClient, + queryOptions as coreQueryOptions, + dataTagSymbol, + skipToken, +} from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' import { assertType, describe, expectTypeOf, it } from 'vitest' import { defaultQueryFn } from '..' @@ -18,6 +23,29 @@ export const exportedQueryOptions = queryOptions({ }) describe('queryOptions', () => { + it('should work when core queryOptions are passed to useQuery', () => { + const options = coreQueryOptions({ + queryKey: createKey(), + queryFn: () => Promise.resolve({ id: '1', title: 'Do Laundry' }), + }) + + const { data } = useQuery(options) + expectTypeOf(data).toEqualTypeOf< + { id: string; title: string } | undefined + >() + }) + + it('should accept core queryOptions with optional initialData in useSuspenseQuery', () => { + const options = coreQueryOptions({ + queryKey: createKey(), + queryFn: () => Promise.resolve(42), + initialData: Math.random() > 0.5 ? 1 : undefined, + }) + + const { data } = useSuspenseQuery(options) + expectTypeOf(data).toEqualTypeOf() + }) + it('should not allow excess properties', () => { assertType( queryOptions({ diff --git a/packages/query-core/src/__tests__/infiniteQueryOptions.test-d.tsx b/packages/query-core/src/__tests__/infiniteQueryOptions.test-d.tsx new file mode 100644 index 00000000000..6d305c27ba5 --- /dev/null +++ b/packages/query-core/src/__tests__/infiniteQueryOptions.test-d.tsx @@ -0,0 +1,220 @@ +import { assertType, describe, expectTypeOf, it } from 'vitest' +import { infiniteQueryOptions } from '../infiniteQueryOptions' +import { QueryClient } from '../queryClient' +import { dataTagErrorSymbol, dataTagSymbol } from '../types' +import { defaultQueryFn, skipToken } from '../utils' +import type { CoreInfiniteQueryOptions, InfiniteData } from '../index' + +// Consumers must be able to emit declarations for exported options. +export const exportedInfiniteOptions = infiniteQueryOptions({ + queryKey: ['exported-infinite'], + queryFn: defaultQueryFn, + initialPageParam: 0, + getNextPageParam: () => undefined, +}) + +describe('infiniteQueryOptions', () => { + it('infers page data and parameters in callbacks and cache APIs', () => { + const options = infiniteQueryOptions({ + queryKey: ['pages'] as const, + initialPageParam: 0, + queryFn: ({ pageParam, queryKey }) => { + expectTypeOf(pageParam).toEqualTypeOf() + expectTypeOf(queryKey).toEqualTypeOf() + return Promise.resolve({ next: pageParam + 1 }) + }, + getNextPageParam: (lastPage, pages, lastParam, params) => { + expectTypeOf(lastPage).toEqualTypeOf<{ next: number }>() + expectTypeOf(pages).toEqualTypeOf>() + expectTypeOf(lastParam).toEqualTypeOf() + expectTypeOf(params).toEqualTypeOf>() + return lastPage.next + }, + getPreviousPageParam: (_firstPage, _pages, firstParam) => firstParam - 1, + enabled: (query) => { + expectTypeOf(query.state.data).toEqualTypeOf< + InfiniteData<{ next: number }, number> | undefined + >() + return true + }, + }) + expectTypeOf(options.queryKey[dataTagSymbol]).toEqualTypeOf< + InfiniteData<{ next: number }, number> + >() + expectTypeOf(options.queryKey[dataTagErrorSymbol]).toEqualTypeOf() + const client = new QueryClient() + expectTypeOf(client.getQueryData(options.queryKey)).toEqualTypeOf< + InfiniteData<{ next: number }, number> | undefined + >() + expectTypeOf(client.infiniteQuery(options)).toEqualTypeOf< + Promise> + >() + client.setQueryData(options.queryKey, { + pages: [{ next: 1 }], + pageParams: [0], + }) + client.setQueryData(options.queryKey, { + pages: [{ next: 1 }], + // @ts-expect-error cached page parameters must be numbers + pageParams: ['0'], + }) + }) + + it('tags raw cached pages when select transforms the result', () => { + const options = infiniteQueryOptions< + { id: string }, + Error & { code: string }, + string, + Array, + string + >({ + queryKey: ['selected-pages'], + initialPageParam: 'first', + queryFn: ({ pageParam }) => Promise.resolve({ id: pageParam }), + getNextPageParam: () => undefined, + select: (data) => data.pages.map((page) => page.id).join(','), + }) + expectTypeOf(options.select).returns.toEqualTypeOf() + expectTypeOf(options.queryKey[dataTagErrorSymbol]).toEqualTypeOf< + Error & { code: string } + >() + expectTypeOf( + new QueryClient().getQueryData(options.queryKey), + ).toEqualTypeOf | undefined>() + expectTypeOf(new QueryClient().infiniteQuery(options)).toEqualTypeOf< + Promise + >() + }) + + it('preserves defined initial data', () => { + const options = infiniteQueryOptions({ + queryKey: ['initial-pages'], + initialPageParam: 0, + queryFn: ({ pageParam }) => Promise.resolve(pageParam), + getNextPageParam: () => undefined, + initialData: { pages: [1], pageParams: [0] }, + }) + expectTypeOf(options.initialData).toEqualTypeOf< + InfiniteData | (() => InfiniteData) + >() + }) + + it('accepts optional initial data without introducing skipToken', () => { + const options = infiniteQueryOptions({ + queryKey: ['optional-pages'], + initialPageParam: 0, + queryFn: ({ pageParam }) => Promise.resolve(pageParam), + getNextPageParam: () => undefined, + initialData: + Math.random() > 0.5 ? { pages: [1], pageParams: [0] } : undefined, + }) + expectTypeOf>().not.toEqualTypeOf< + typeof skipToken + >() + expectTypeOf(options.initialData).toExtend< + | InfiniteData + | (() => InfiniteData | undefined) + | undefined + >() + }) + + it('supports skipToken', () => { + const options = infiniteQueryOptions({ + queryKey: ['skipped'], + initialPageParam: 0, + queryFn: skipToken, + getNextPageParam: () => undefined, + }) + expectTypeOf(options.queryKey[dataTagSymbol]).toEqualTypeOf< + InfiniteData + >() + }) + + it('supports conditional skipToken', () => { + const options = infiniteQueryOptions({ + queryKey: ['skipped-pages'], + initialPageParam: 0, + queryFn: + Math.random() > 0.5 + ? ({ pageParam }) => Promise.resolve(pageParam) + : skipToken, + getNextPageParam: () => undefined, + }) + expectTypeOf(options.queryKey[dataTagSymbol]).toEqualTypeOf< + InfiniteData + >() + }) + + it('requires pagination options and rejects excess properties', () => { + assertType( + // @ts-expect-error initialPageParam is required + infiniteQueryOptions({ + queryKey: ['missing-param'], + queryFn: () => Promise.resolve(1), + getNextPageParam: () => undefined, + }), + ) + assertType( + // @ts-expect-error getNextPageParam is required + infiniteQueryOptions({ + queryKey: ['missing-next'], + queryFn: () => Promise.resolve(1), + initialPageParam: 0, + }), + ) + assertType( + // @ts-expect-error queryFn is required + infiniteQueryOptions({ + queryKey: ['missing-query-fn'], + initialPageParam: 0, + getNextPageParam: () => undefined, + }), + ) + assertType( + infiniteQueryOptions({ + queryKey: ['excess'], + queryFn: () => Promise.resolve(1), + initialPageParam: 0, + getNextPageParam: () => undefined, + // @ts-expect-error misspelled option + stallTime: 1000, + }), + ) + expectTypeOf>().toHaveProperty( + 'initialPageParam', + ) + }) + + it('does not allow framework-specific options', () => { + assertType( + infiniteQueryOptions({ + queryKey: ['framework'], + queryFn: () => Promise.resolve(1), + initialPageParam: 0, + getNextPageParam: () => undefined, + // @ts-expect-error throwOnError depends on the framework adapter + throwOnError: true, + }), + ) + assertType( + infiniteQueryOptions({ + queryKey: ['framework'], + queryFn: () => Promise.resolve(1), + initialPageParam: 0, + getNextPageParam: () => undefined, + // @ts-expect-error suspense depends on the framework adapter + suspense: true, + }), + ) + assertType( + infiniteQueryOptions({ + queryKey: ['framework'], + queryFn: () => Promise.resolve(1), + initialPageParam: 0, + getNextPageParam: () => undefined, + // @ts-expect-error notifyOnChangeProps depends on the framework adapter + notifyOnChangeProps: ['data'], + }), + ) + }) +}) diff --git a/packages/query-core/src/__tests__/infiniteQueryOptions.test.ts b/packages/query-core/src/__tests__/infiniteQueryOptions.test.ts new file mode 100644 index 00000000000..e621a41db9a --- /dev/null +++ b/packages/query-core/src/__tests__/infiniteQueryOptions.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from 'vitest' +import { infiniteQueryOptions } from '../infiniteQueryOptions' +import { QueryClient } from '../queryClient' + +describe('infiniteQueryOptions', () => { + it('should return the options unchanged and fetch pages with the query client', async () => { + const options = { + queryKey: ['core-infinite-options'], + initialPageParam: 0, + queryFn: ({ pageParam }: { pageParam: number }) => + Promise.resolve(pageParam), + getNextPageParam: (lastPage: number) => lastPage + 1, + } + expect(infiniteQueryOptions(options)).toBe(options) + const client = new QueryClient() + await expect( + client.infiniteQuery({ ...infiniteQueryOptions(options), pages: 2 }), + ).resolves.toStrictEqual({ pages: [0, 1], pageParams: [0, 1] }) + client.clear() + }) +}) diff --git a/packages/query-core/src/__tests__/mutationOptions.test-d.tsx b/packages/query-core/src/__tests__/mutationOptions.test-d.tsx new file mode 100644 index 00000000000..ef40671c5dc --- /dev/null +++ b/packages/query-core/src/__tests__/mutationOptions.test-d.tsx @@ -0,0 +1,91 @@ +import { assertType, describe, expectTypeOf, it } from 'vitest' +import { mutationOptions } from '../mutationOptions' +import type { CoreMutationOptions } from '../index' + +describe('mutationOptions', () => { + it('should infer mutation data and variables', () => { + const options = mutationOptions({ + mutationFn: (variables: { id: string }) => Promise.resolve(variables.id), + onSuccess: (data, variables) => { + expectTypeOf(data).toEqualTypeOf() + expectTypeOf(variables).toEqualTypeOf<{ id: string }>() + }, + }) + + expectTypeOf(options.mutationFn) + .parameter(0) + .toEqualTypeOf<{ id: string }>() + type MutationFn = NonNullable + expectTypeOf>>().toEqualTypeOf() + expectTypeOf(options).not.toHaveProperty('mutationKey') + }) + + it('should preserve a required mutationKey', () => { + const options = mutationOptions({ + mutationKey: ['key'], + mutationFn: (variables: { id: string }) => Promise.resolve(variables.id), + }) + + expectTypeOf(options.mutationKey).toEqualTypeOf>() + }) + + it('should accept an optional mutationKey in an object literal', () => { + const options = mutationOptions({ + mutationKey: Math.random() > 0.5 ? ['key'] : undefined, + mutationFn: (variables: { id: string }) => Promise.resolve(variables.id), + onMutate: (variables) => ({ previous: variables.id }), + onSuccess: (data, variables, onMutateResult) => { + expectTypeOf(data).toEqualTypeOf() + expectTypeOf(variables).toEqualTypeOf<{ id: string }>() + expectTypeOf(onMutateResult).toEqualTypeOf<{ previous: string }>() + }, + }) + + expectTypeOf(options.mutationKey).toEqualTypeOf< + ReadonlyArray | undefined + >() + }) + + it('should preserve an optional mutationKey in typed options', () => { + const input: CoreMutationOptions = { + mutationKey: Math.random() > 0.5 ? ['key'] : undefined, + mutationFn: (variables) => Promise.resolve(variables.id), + } + const options = mutationOptions(input) + + expectTypeOf(options).toEqualTypeOf< + CoreMutationOptions + >() + expectTypeOf(options.mutationKey).toEqualTypeOf< + ReadonlyArray | undefined + >() + }) + + it('should export the reusable mutation options type', () => { + expectTypeOf< + CoreMutationOptions + >().toHaveProperty('mutationFn') + }) + + it('should not allow _defaulted', () => { + expectTypeOf(mutationOptions).parameter(0).not.toHaveProperty('_defaulted') + + assertType( + mutationOptions({ + mutationFn: () => Promise.resolve(5), + // @ts-expect-error _defaulted is an internal option + _defaulted: true, + }), + ) + }) + + it('should not allow throwOnError', () => { + assertType( + mutationOptions({ + mutationFn: () => Promise.resolve(5), + // @ts-expect-error throwOnError depends on the framework adapter + throwOnError: true, + }), + ) + }) +}) diff --git a/packages/query-core/src/__tests__/mutationOptions.test.ts b/packages/query-core/src/__tests__/mutationOptions.test.ts new file mode 100644 index 00000000000..1529d844dd5 --- /dev/null +++ b/packages/query-core/src/__tests__/mutationOptions.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from 'vitest' +import { MutationObserver } from '../mutationObserver' +import { mutationOptions } from '../mutationOptions' +import { QueryClient } from '../queryClient' + +describe('mutationOptions', () => { + it('should return the options unchanged and work with a mutation observer', async () => { + const options = { + mutationFn: (variables: { id: string }) => Promise.resolve(variables.id), + } + expect(mutationOptions(options)).toBe(options) + const client = new QueryClient() + const observer = new MutationObserver(client, mutationOptions(options)) + await expect(observer.mutate({ id: '1' })).resolves.toBe('1') + client.clear() + }) +}) diff --git a/packages/query-core/src/__tests__/queryOptions.test-d.tsx b/packages/query-core/src/__tests__/queryOptions.test-d.tsx new file mode 100644 index 00000000000..2462160e452 --- /dev/null +++ b/packages/query-core/src/__tests__/queryOptions.test-d.tsx @@ -0,0 +1,183 @@ +import { assertType, describe, expectTypeOf, it } from 'vitest' +import { QueryClient } from '../queryClient' +import { queryOptions } from '../queryOptions' +import { dataTagErrorSymbol, dataTagSymbol } from '../types' +import { defaultQueryFn, skipToken } from '../utils' + +// Verify consumers can export options without inaccessible data tag symbols. +export const exportedQueryOptions = queryOptions({ + queryKey: ['exported'], + queryFn: defaultQueryFn, +}) + +describe('queryOptions', () => { + it('should not allow excess properties', () => { + assertType( + queryOptions({ + queryKey: ['key'], + queryFn: () => Promise.resolve(5), + // @ts-expect-error stallTime does not exist + stallTime: 1000, + }), + ) + }) + + it('should not allow framework-specific options', () => { + assertType( + queryOptions({ + queryKey: ['key'], + queryFn: () => Promise.resolve(5), + // @ts-expect-error throwOnError depends on the framework adapter + throwOnError: true, + }), + ) + assertType( + queryOptions({ + queryKey: ['key'], + queryFn: () => Promise.resolve(5), + // @ts-expect-error suspense depends on the framework adapter + suspense: true, + }), + ) + assertType( + queryOptions({ + queryKey: ['key'], + queryFn: () => Promise.resolve(5), + // @ts-expect-error notifyOnChangeProps depends on the framework adapter + notifyOnChangeProps: ['data'], + }), + ) + }) + + it('should require queryFn', () => { + // @ts-expect-error queryFn is required + assertType(queryOptions({ queryKey: ['key'] })) + }) + + it('should preserve raw cache data when select transforms the observer result', () => { + const options = queryOptions({ + queryKey: ['selected'], + queryFn: () => Promise.resolve({ id: 1 }), + select: (data) => data.id.toString(), + }) + expectTypeOf(options.select).returns.toEqualTypeOf() + expectTypeOf( + new QueryClient().getQueryData(options.queryKey), + ).toEqualTypeOf<{ id: number } | undefined>() + }) + + it('should accept optional initialData without promising defined data', () => { + const options = queryOptions({ + queryKey: ['optional-initial-data'], + queryFn: () => Promise.resolve('fetched'), + initialData: Math.random() > 0.5 ? 'initial' : undefined, + }) + expectTypeOf(options.initialData).toExtend< + string | (() => string | undefined) | undefined + >() + expectTypeOf(options.queryKey[dataTagSymbol]).toEqualTypeOf() + }) + + it('should infer query data from queryFn', () => { + const options = queryOptions({ + queryKey: ['key'], + queryFn: () => Promise.resolve(5), + }) + + type QueryFn = Exclude + + expectTypeOf>>().toEqualTypeOf() + expectTypeOf(options.queryKey[dataTagSymbol]).toEqualTypeOf() + expectTypeOf(options.queryKey[dataTagErrorSymbol]).toEqualTypeOf() + }) + + it('should type check values passed to setQueryData from the tagged queryKey', () => { + const options = queryOptions({ + queryKey: ['todo'], + queryFn: () => Promise.resolve({ id: '1', title: 'Do Laundry' }), + }) + const queryClient = new QueryClient() + + queryClient.setQueryData(options.queryKey, { + id: '1', + title: 'Wash dishes', + }) + + queryClient.setQueryData(options.queryKey, (prev) => { + expectTypeOf(prev).toEqualTypeOf< + { id: string; title: string } | undefined + >() + return prev + }) + + // @ts-expect-error title should be a string + queryClient.setQueryData(options.queryKey, { id: '1', title: 1 }) + + // @ts-expect-error title is required + queryClient.setQueryData(options.queryKey, { id: '1' }) + }) + + it('should infer data from initialData with defaultQueryFn', () => { + const options = queryOptions({ + queryKey: ['key'], + queryFn: defaultQueryFn, + initialData: 1, + }) + + expectTypeOf(options.queryKey[dataTagSymbol]).toEqualTypeOf() + expectTypeOf( + new QueryClient().getQueryData(options.queryKey), + ).toEqualTypeOf() + }) + + it('should infer data when initialData is undefined', () => { + const options = queryOptions({ + queryKey: ['key'], + queryFn: () => Promise.resolve(5), + initialData: undefined, + }) + + expectTypeOf(options.queryKey[dataTagSymbol]).toEqualTypeOf() + }) + + it('should infer a callable queryFn without skipToken', () => { + const options = queryOptions({ + queryKey: ['key'], + queryFn: () => Promise.resolve(5), + enabled: false, + }) + + expectTypeOf(options.queryFn).not.toEqualTypeOf() + expectTypeOf(options.queryKey[dataTagSymbol]).toEqualTypeOf() + }) + + it('should allow skipToken', () => { + const options = queryOptions({ + queryKey: ['key'], + queryFn: skipToken, + }) + + expectTypeOf(options.queryKey[dataTagSymbol]).toEqualTypeOf() + }) + + it('should work when passed to query', async () => { + const options = queryOptions({ + queryKey: ['key'], + queryFn: () => Promise.resolve(5), + select: (data) => data.toString(), + }) + + const data = await new QueryClient().query(options) + expectTypeOf(data).toEqualTypeOf() + }) + + it('should allow undefined data in query when queryFn can be skipToken', async () => { + const options = queryOptions({ + queryKey: ['key'], + queryFn: Math.random() > 0.5 ? skipToken : () => Promise.resolve(5), + }) + + const data = await new QueryClient().query(options) + expectTypeOf(data).toEqualTypeOf() + }) +}) diff --git a/packages/query-core/src/__tests__/queryOptions.test.ts b/packages/query-core/src/__tests__/queryOptions.test.ts new file mode 100644 index 00000000000..e314e034f45 --- /dev/null +++ b/packages/query-core/src/__tests__/queryOptions.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from 'vitest' +import { QueryClient } from '../queryClient' +import { queryOptions } from '../queryOptions' + +describe('queryOptions', () => { + it('should return the options unchanged and work with the query client', async () => { + const options = { + queryKey: ['core-options'], + queryFn: () => Promise.resolve(42), + } + expect(queryOptions(options)).toBe(options) + const client = new QueryClient() + await expect(client.query(queryOptions(options))).resolves.toBe(42) + expect(client.getQueryData(options.queryKey)).toBe(42) + client.clear() + }) +}) diff --git a/packages/query-core/src/index.ts b/packages/query-core/src/index.ts index 0b313930aa5..de2de2f792f 100644 --- a/packages/query-core/src/index.ts +++ b/packages/query-core/src/index.ts @@ -52,6 +52,12 @@ export type { } from './utils' export { streamedQuery } from './streamedQuery' +export { queryOptions } from './queryOptions' +export type { CoreQueryOptions } from './queryOptions' +export { infiniteQueryOptions } from './infiniteQueryOptions' +export type { CoreInfiniteQueryOptions } from './infiniteQueryOptions' +export { mutationOptions } from './mutationOptions' +export type { CoreMutationOptions } from './mutationOptions' // Types export type { diff --git a/packages/query-core/src/infiniteQueryOptions.ts b/packages/query-core/src/infiniteQueryOptions.ts new file mode 100644 index 00000000000..66ed6ad190e --- /dev/null +++ b/packages/query-core/src/infiniteQueryOptions.ts @@ -0,0 +1,227 @@ +import type { AdapterQueryObserverOptionKeys } from './queryOptions' +import type { + DefaultError, + InfiniteData, + InfiniteQueryObserverOptions, + InitialDataFunction, + NonUndefinedGuard, + OmitKeyof, + QueryKey, + QueryKeyWithDataTag, +} from './types' +import type { SkipToken } from './utils' + +/** + * The {@link InfiniteQueryObserverOptions} that every framework adapter supports. Options that depend on a + * framework, such as `throwOnError`, `suspense`, and `notifyOnChangeProps`, are left out. Use the + * `infiniteQueryOptions` helper of your adapter when you need them. + * @template TQueryFnData - The type your `queryFn` resolves to (a single page). + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. + * @template TQueryKey - The type of your `queryKey`. + * @template TPageParam - The type of the page parameter. + */ +export type CoreInfiniteQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = OmitKeyof< + InfiniteQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + AdapterQueryObserverOptionKeys +> + +/** + * The options accepted by the `infiniteQueryOptions` overload selected when `initialData` is omitted, may be + * `undefined`, or is a function that may return `undefined`. + * @template TQueryFnData - The type your `queryFn` resolves to (a single page). + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. + * @template TQueryKey - The type of your `queryKey`. + * @template TPageParam - The type of the page parameter. + */ +export type UndefinedInitialDataInfiniteOptions< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = CoreInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> & { + initialData?: + | undefined + | NonUndefinedGuard> + | InitialDataFunction< + NonUndefinedGuard> + > +} + +/** + * The options accepted by the `infiniteQueryOptions` overload selected when `queryFn` is not `skipToken`. + * Same as {@link UndefinedInitialDataInfiniteOptions}, but `queryFn` may not be `skipToken`. + * @template TQueryFnData - The type your `queryFn` resolves to (a single page). + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. + * @template TQueryKey - The type of your `queryKey`. + * @template TPageParam - The type of the page parameter. + */ +export type UnusedSkipTokenInfiniteOptions< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = OmitKeyof< + CoreInfiniteQueryOptions, + 'queryFn' +> & { + queryFn: Exclude< + CoreInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >['queryFn'], + SkipToken + > +} + +/** + * The options accepted by the `infiniteQueryOptions` overload selected when `initialData` is known to be + * defined. + * @template TQueryFnData - The type your `queryFn` resolves to (a single page). + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. + * @template TQueryKey - The type of your `queryKey`. + * @template TPageParam - The type of the page parameter. + */ +export type DefinedInitialDataInfiniteOptions< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = OmitKeyof< + CoreInfiniteQueryOptions, + 'initialData' +> & { + initialData: + | NonUndefinedGuard> + | (() => NonUndefinedGuard>) +} + +/** + * Defines infinite query options that can be shared between framework adapters and imperative APIs such as + * `queryClient.infiniteQuery`. At runtime, it returns the options unchanged. + * + * Only {@link CoreInfiniteQueryOptions} are accepted. Use the `infiniteQueryOptions` helper of your adapter + * for framework-specific options such as `throwOnError`. + * + * This overload is selected when `initialData` is known to be defined. + * @param options - The {@link DefinedInitialDataInfiniteOptions} to use. + * @returns The same options object, typed so that `queryKey` carries the inferred pages and page parameters. + */ +export function infiniteQueryOptions< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: DefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, +): DefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> & + QueryKeyWithDataTag, TError> + +/** + * Defines infinite query options that can be shared between framework adapters and imperative APIs such as + * `queryClient.infiniteQuery`. At runtime, it returns the options unchanged. + * + * Only {@link CoreInfiniteQueryOptions} are accepted. Use the `infiniteQueryOptions` helper of your adapter + * for framework-specific options such as `throwOnError`. + * @param options - The {@link UnusedSkipTokenInfiniteOptions} to use. + * @returns The same options object, typed so that `queryKey` carries the inferred pages and page parameters. + */ +export function infiniteQueryOptions< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: UnusedSkipTokenInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, +): UnusedSkipTokenInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> & + QueryKeyWithDataTag, TError> + +/** + * Defines infinite query options that can be shared between framework adapters and imperative APIs such as + * `queryClient.infiniteQuery`. At runtime, it returns the options unchanged. + * + * Only {@link CoreInfiniteQueryOptions} are accepted. Use the `infiniteQueryOptions` helper of your adapter + * for framework-specific options such as `throwOnError`. + * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use. + * @returns The same options object, typed so that `queryKey` carries the inferred pages and page parameters. + * @remarks This is the only overload that accepts `queryFn: skipToken`. + */ +export function infiniteQueryOptions< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: UndefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, +): UndefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> & + QueryKeyWithDataTag, TError> + +export function infiniteQueryOptions(options: unknown) { + return options +} diff --git a/packages/query-core/src/mutationOptions.ts b/packages/query-core/src/mutationOptions.ts new file mode 100644 index 00000000000..5978533f967 --- /dev/null +++ b/packages/query-core/src/mutationOptions.ts @@ -0,0 +1,94 @@ +import type { + DefaultError, + MutationOptions, + OmitKeyof, + WithRequired, +} from './types' + +/** + * The {@link MutationOptions} that every framework adapter supports. Options that depend on a framework, + * such as `throwOnError`, are left out. Use the `mutationOptions` helper of your adapter when you need them. + * @template TData - The type your `mutationFn` resolves to. + * @template TError - The type of errors your `mutationFn` may throw. + * @template TVariables - The type of the variables passed to `mutate`. + * @template TOnMutateResult - The type `onMutate` returns. + */ +export type CoreMutationOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = OmitKeyof< + MutationOptions, + '_defaulted' +> + +/** + * Defines mutation options that can be shared between framework adapters and imperative APIs such as + * `MutationObserver`. At runtime, it returns the options unchanged. + * + * Only {@link CoreMutationOptions} are accepted. Use the `mutationOptions` helper of your adapter for + * framework-specific options such as `throwOnError`. + * @param options - The mutation options to use, with a `mutationKey`. + * @returns The same options object, with inferred types. + */ +export function mutationOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +>( + options: WithRequired< + CoreMutationOptions, + 'mutationKey' + >, +): WithRequired< + CoreMutationOptions, + 'mutationKey' +> + +/** + * Defines mutation options that can be shared between framework adapters and imperative APIs such as + * `MutationObserver`. At runtime, it returns the options unchanged. + * + * Only {@link CoreMutationOptions} are accepted. Use the `mutationOptions` helper of your adapter for + * framework-specific options such as `throwOnError`. + * @param options - The mutation options to use, without a `mutationKey`. + * @returns The same options object, with inferred types. + */ +export function mutationOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +>( + options: Omit< + CoreMutationOptions, + 'mutationKey' + > & { mutationKey?: never }, +): Omit< + CoreMutationOptions, + 'mutationKey' +> + +/** + * Defines mutation options that can be shared between framework adapters and imperative APIs such as + * `MutationObserver`. At runtime, it returns the options unchanged. + * + * Only {@link CoreMutationOptions} are accepted. Use the `mutationOptions` helper of your adapter for + * framework-specific options such as `throwOnError`. + * @param options - The mutation options to use, with an optional `mutationKey`. + * @returns The same options object, with inferred types. + */ +export function mutationOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +>( + options: CoreMutationOptions, +): CoreMutationOptions + +export function mutationOptions(options: unknown) { + return options +} diff --git a/packages/query-core/src/queryOptions.ts b/packages/query-core/src/queryOptions.ts new file mode 100644 index 00000000000..24469f7dbe5 --- /dev/null +++ b/packages/query-core/src/queryOptions.ts @@ -0,0 +1,177 @@ +import type { + DefaultError, + InitialDataFunction, + NonUndefinedGuard, + OmitKeyof, + QueryFunction, + QueryKey, + QueryKeyWithDataTag, + QueryObserverOptions, +} from './types' +import type { DefaultQueryFn, SkipToken } from './utils' + +/** + * Observer options that the core helpers leave out: options whose behavior depends on the framework + * adapter, and internal options. + * @internal + */ +export type AdapterQueryObserverOptionKeys = + | 'throwOnError' + | 'suspense' + | 'notifyOnChangeProps' + | 'behavior' + | '_defaulted' + | '_type' + | '_optimisticResults' + +/** + * The {@link QueryObserverOptions} that every framework adapter supports. Options that depend on a + * framework, such as `throwOnError`, `suspense`, and `notifyOnChangeProps`, are left out. Use the + * `queryOptions` helper of your adapter when you need them. + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. + * @template TQueryKey - The type of your `queryKey`. + */ +export type CoreQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = OmitKeyof< + QueryObserverOptions, + AdapterQueryObserverOptionKeys +> + +/** + * The options accepted by the `queryOptions` overload selected when `initialData` is omitted, may be + * `undefined`, or is a function that may return `undefined`. `data` may be `undefined` while the query is + * `pending`. + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. + * @template TQueryKey - The type of your `queryKey`. + */ +export type UndefinedInitialDataOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = CoreQueryOptions & { + initialData?: + | undefined + | InitialDataFunction> + | NonUndefinedGuard +} + +/** + * The options accepted by the `queryOptions` overload selected when `queryFn` is not `skipToken` and + * `initialData` is omitted, may be `undefined`, or is a function that may return `undefined`. Same as + * {@link UndefinedInitialDataOptions}, but `queryFn` may not be `skipToken`. + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. + * @template TQueryKey - The type of your `queryKey`. + */ +export type UnusedSkipTokenOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = OmitKeyof< + CoreQueryOptions, + 'queryFn' +> & { + queryFn: Exclude< + CoreQueryOptions['queryFn'], + SkipToken + > +} + +/** + * The options accepted by the `queryOptions` overload selected when `initialData` is known to be defined. + * `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`). + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. + * @template TQueryKey - The type of your `queryKey`. + */ +export type DefinedInitialDataOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = OmitKeyof< + CoreQueryOptions, + 'queryFn' +> & { + initialData: + | NonUndefinedGuard + | (() => NonUndefinedGuard) + queryFn: QueryFunction | DefaultQueryFn +} + +/** + * Defines query options that can be shared between framework adapters and imperative APIs such as + * `queryClient.query`. At runtime, it returns the options unchanged. + * + * Only {@link CoreQueryOptions} are accepted. Use the `queryOptions` helper of your adapter for + * framework-specific options such as `throwOnError`. + * + * This overload is selected when `initialData` is known to be defined, so the resulting `data` is never + * `undefined` (unless a `select` changes `TData` to include `undefined`). + * @param options - The {@link DefinedInitialDataOptions} to use. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + */ +export function queryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: DefinedInitialDataOptions, +): DefinedInitialDataOptions & + QueryKeyWithDataTag + +/** + * Defines query options that can be shared between framework adapters and imperative APIs such as + * `queryClient.query`. At runtime, it returns the options unchanged. + * + * Only {@link CoreQueryOptions} are accepted. Use the `queryOptions` helper of your adapter for + * framework-specific options such as `throwOnError`. + * @param options - The {@link UnusedSkipTokenOptions} to use. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + */ +export function queryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: UnusedSkipTokenOptions, +): UnusedSkipTokenOptions & + QueryKeyWithDataTag + +/** + * Defines query options that can be shared between framework adapters and imperative APIs such as + * `queryClient.query`. At runtime, it returns the options unchanged. + * + * Only {@link CoreQueryOptions} are accepted. Use the `queryOptions` helper of your adapter for + * framework-specific options such as `throwOnError`. + * @param options - The {@link UndefinedInitialDataOptions} to use. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @remarks This is the only overload that accepts `queryFn: skipToken`. + */ +export function queryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: UndefinedInitialDataOptions, +): UndefinedInitialDataOptions & + QueryKeyWithDataTag + +export function queryOptions(options: unknown) { + return options +} diff --git a/packages/react-query/src/__tests__/infiniteQueryOptions.test-d.tsx b/packages/react-query/src/__tests__/infiniteQueryOptions.test-d.tsx index b9e0ccc680f..178c4a37cf5 100644 --- a/packages/react-query/src/__tests__/infiniteQueryOptions.test-d.tsx +++ b/packages/react-query/src/__tests__/infiniteQueryOptions.test-d.tsx @@ -1,4 +1,9 @@ -import { QueryClient, dataTagSymbol, skipToken } from '@tanstack/query-core' +import { + QueryClient, + infiniteQueryOptions as coreInfiniteQueryOptions, + dataTagSymbol, + skipToken, +} from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' import { assertType, describe, expectTypeOf, it } from 'vitest' import { defaultQueryFn } from '..' @@ -23,6 +28,44 @@ export const exportedInfiniteQueryOptions = infiniteQueryOptions({ }) describe('infiniteQueryOptions', () => { + it('should accept core options with optional initialData in suspense', () => { + const options = coreInfiniteQueryOptions({ + queryKey: createKey(), + initialPageParam: 0, + queryFn: ({ pageParam }) => Promise.resolve(pageParam), + getNextPageParam: () => undefined, + initialData: + Math.random() > 0.5 ? { pages: [1], pageParams: [0] } : undefined, + }) + expectTypeOf(useSuspenseInfiniteQuery(options).data).toEqualTypeOf< + InfiniteData + >() + }) + + it('should infer data from core infiniteQueryOptions', () => { + const options = coreInfiniteQueryOptions({ + queryKey: createKey(), + initialPageParam: 0, + queryFn: ({ pageParam }) => Promise.resolve(pageParam), + getNextPageParam: () => undefined, + }) + const query = useInfiniteQuery(options) + expectTypeOf(query.data).toEqualTypeOf | undefined>() + }) + + it('should preserve selected data and initialData from core infiniteQueryOptions', () => { + const options = coreInfiniteQueryOptions({ + queryKey: createKey(), + initialPageParam: 0, + queryFn: ({ pageParam }) => Promise.resolve(pageParam), + getNextPageParam: () => undefined, + initialData: { pages: [1], pageParams: [0] }, + select: (data) => data.pages.length, + }) + const query = useInfiniteQuery(options) + expectTypeOf(query.data).toEqualTypeOf() + }) + it('should not allow excess properties', () => { assertType( infiniteQueryOptions({ diff --git a/packages/react-query/src/__tests__/mutationOptions.test-d.tsx b/packages/react-query/src/__tests__/mutationOptions.test-d.tsx index 8085b19433d..fb3060b8f0a 100644 --- a/packages/react-query/src/__tests__/mutationOptions.test-d.tsx +++ b/packages/react-query/src/__tests__/mutationOptions.test-d.tsx @@ -1,4 +1,7 @@ -import { QueryClient } from '@tanstack/query-core' +import { + QueryClient, + mutationOptions as coreMutationOptions, +} from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' import { assertType, describe, expectTypeOf, it } from 'vitest' import { useIsMutating, useMutation, useMutationState } from '..' @@ -161,6 +164,18 @@ describe('mutationOptions', () => { ) }) + it('should infer types when core mutationOptions are used with useMutation', () => { + const mutation = useMutation( + coreMutationOptions({ + mutationFn: (input: { id: string }) => Promise.resolve(input.id), + }), + ) + + expectTypeOf(mutation.data).toEqualTypeOf() + expectTypeOf(mutation.variables).toEqualTypeOf<{ id: string } | undefined>() + expectTypeOf(mutation.mutate).toBeCallableWith({ id: '1' }) + }) + it('should infer types when used with useIsMutating', () => { const isMutating = useIsMutating( mutationOptions({ diff --git a/packages/react-query/src/__tests__/queryOptions.test-d.tsx b/packages/react-query/src/__tests__/queryOptions.test-d.tsx index b48d2dd7259..ba2f314f830 100644 --- a/packages/react-query/src/__tests__/queryOptions.test-d.tsx +++ b/packages/react-query/src/__tests__/queryOptions.test-d.tsx @@ -1,4 +1,9 @@ -import { QueryClient, dataTagSymbol, skipToken } from '@tanstack/query-core' +import { + QueryClient, + queryOptions as coreQueryOptions, + dataTagSymbol, + skipToken, +} from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' import { assertType, describe, expectTypeOf, it } from 'vitest' import { defaultQueryFn } from '..' @@ -22,6 +27,29 @@ export const exportedQueryOptions = queryOptions({ }) describe('queryOptions', () => { + it('should work when core queryOptions are passed to useQuery', () => { + const options = coreQueryOptions({ + queryKey: createKey(), + queryFn: () => Promise.resolve({ id: '1', title: 'Do Laundry' }), + }) + + const { data } = useQuery(options) + expectTypeOf(data).toEqualTypeOf< + { id: string; title: string } | undefined + >() + }) + + it('should accept core queryOptions with optional initialData in useSuspenseQuery', () => { + const options = coreQueryOptions({ + queryKey: createKey(), + queryFn: () => Promise.resolve(42), + initialData: Math.random() > 0.5 ? 1 : undefined, + }) + + const { data } = useSuspenseQuery(options) + expectTypeOf(data).toEqualTypeOf() + }) + it('should not allow excess properties', () => { assertType( queryOptions({ diff --git a/packages/solid-query/src/__tests__/infiniteQueryOptions.test-d.tsx b/packages/solid-query/src/__tests__/infiniteQueryOptions.test-d.tsx index c44edaedca0..70facd1474b 100644 --- a/packages/solid-query/src/__tests__/infiniteQueryOptions.test-d.tsx +++ b/packages/solid-query/src/__tests__/infiniteQueryOptions.test-d.tsx @@ -1,4 +1,9 @@ -import { QueryClient, dataTagSymbol, skipToken } from '@tanstack/query-core' +import { + QueryClient, + infiniteQueryOptions as coreInfiniteQueryOptions, + dataTagSymbol, + skipToken, +} from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' import { describe, expectTypeOf, it } from 'vitest' import { defaultQueryFn } from '..' @@ -21,6 +26,30 @@ export const exportedInfiniteQueryOptions = infiniteQueryOptions({ }) describe('infiniteQueryOptions', () => { + it('should infer data from core infiniteQueryOptions', () => { + const options = coreInfiniteQueryOptions({ + queryKey: createKey(), + initialPageParam: 0, + queryFn: ({ pageParam }) => Promise.resolve(pageParam), + getNextPageParam: () => undefined, + }) + const query = useInfiniteQuery(() => options) + expectTypeOf(query.data).toEqualTypeOf | undefined>() + }) + + it('should preserve selected data and initialData from core infiniteQueryOptions', () => { + const options = coreInfiniteQueryOptions({ + queryKey: createKey(), + initialPageParam: 0, + queryFn: ({ pageParam }) => Promise.resolve(pageParam), + getNextPageParam: () => undefined, + initialData: { pages: [1], pageParams: [0] }, + select: (data) => data.pages.length, + }) + const query = useInfiniteQuery(() => options) + expectTypeOf(query.data).toEqualTypeOf() + }) + it('should work when passed to infiniteQuery', async () => { const options = infiniteQueryOptions({ getNextPageParam: () => 10, diff --git a/packages/solid-query/src/__tests__/mutationOptions.test-d.tsx b/packages/solid-query/src/__tests__/mutationOptions.test-d.tsx index 3de03dae93c..cbb35fd219c 100644 --- a/packages/solid-query/src/__tests__/mutationOptions.test-d.tsx +++ b/packages/solid-query/src/__tests__/mutationOptions.test-d.tsx @@ -1,4 +1,7 @@ -import { QueryClient } from '@tanstack/query-core' +import { + QueryClient, + mutationOptions as coreMutationOptions, +} from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' import { assertType, describe, expectTypeOf, it } from 'vitest' import { useIsMutating, useMutation, useMutationState } from '..' @@ -158,6 +161,18 @@ describe('mutationOptions', () => { ) }) + it('should infer types when core mutationOptions are used with useMutation', () => { + const mutation = useMutation(() => + coreMutationOptions({ + mutationFn: (input: { id: string }) => Promise.resolve(input.id), + }), + ) + + expectTypeOf(mutation.data).toEqualTypeOf() + expectTypeOf(mutation.variables).toEqualTypeOf<{ id: string } | undefined>() + expectTypeOf(mutation.mutate).toBeCallableWith({ id: '1' }) + }) + it('should infer types when used with useIsMutating', () => { const isMutating = useIsMutating(() => mutationOptions({ diff --git a/packages/solid-query/src/__tests__/queryOptions.test-d.tsx b/packages/solid-query/src/__tests__/queryOptions.test-d.tsx index ca298a5039c..3b739c13f0d 100644 --- a/packages/solid-query/src/__tests__/queryOptions.test-d.tsx +++ b/packages/solid-query/src/__tests__/queryOptions.test-d.tsx @@ -1,5 +1,6 @@ import { QueryClient, + queryOptions as coreQueryOptions, dataTagErrorSymbol, dataTagSymbol, skipToken, @@ -20,6 +21,18 @@ export const exportedQueryOptions = queryOptions({ }) describe('queryOptions', () => { + it('should work when core queryOptions are passed to useQuery', () => { + const options = coreQueryOptions({ + queryKey: createKey(), + queryFn: () => Promise.resolve({ id: '1', title: 'Do Laundry' }), + }) + + const { data } = useQuery(() => options) + expectTypeOf(data).toEqualTypeOf< + { id: string; title: string } | undefined + >() + }) + it('should not allow excess properties', () => { assertType( queryOptions({ diff --git a/packages/svelte-query/tests/createQuery/createQuery.test-d.ts b/packages/svelte-query/tests/createQuery/createQuery.test-d.ts index 5a9463a2859..f53e7308127 100644 --- a/packages/svelte-query/tests/createQuery/createQuery.test-d.ts +++ b/packages/svelte-query/tests/createQuery/createQuery.test-d.ts @@ -1,8 +1,21 @@ +import { queryOptions as coreQueryOptions } from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' import { describe, expectTypeOf, it } from 'vitest' import { createQuery, queryOptions } from '../../src/index.js' describe('createQuery', () => { + it('should infer data from core queryOptions', () => { + const options = coreQueryOptions({ + queryKey: createKey(), + queryFn: () => Promise.resolve({ id: '1', title: 'Do Laundry' }), + }) + + const { data } = createQuery(() => options) + expectTypeOf(data).toEqualTypeOf< + { id: string; title: string } | undefined + >() + }) + it('should return the correct states for a successful query', () => { const key = createKey() const query = createQuery(() => ({ diff --git a/packages/svelte-query/tests/infiniteQueryOptions.test-d.ts b/packages/svelte-query/tests/infiniteQueryOptions.test-d.ts index ce10cf38fbf..d67bc6e98f1 100644 --- a/packages/svelte-query/tests/infiniteQueryOptions.test-d.ts +++ b/packages/svelte-query/tests/infiniteQueryOptions.test-d.ts @@ -1,10 +1,38 @@ -import { QueryClient, skipToken } from '@tanstack/query-core' +import { + QueryClient, + infiniteQueryOptions as coreInfiniteQueryOptions, + skipToken, +} from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' import { assertType, describe, expectTypeOf, it } from 'vitest' import { createInfiniteQuery, infiniteQueryOptions } from '../src/index.js' import type { InfiniteData } from '@tanstack/query-core' describe('infiniteQueryOptions', () => { + it('should infer data from core infiniteQueryOptions', () => { + const options = coreInfiniteQueryOptions({ + queryKey: createKey(), + initialPageParam: 0, + queryFn: ({ pageParam }) => Promise.resolve(pageParam), + getNextPageParam: () => undefined, + }) + const query = createInfiniteQuery(() => options) + expectTypeOf(query.data).toEqualTypeOf | undefined>() + }) + + it('should preserve selected data and initialData from core infiniteQueryOptions', () => { + const options = coreInfiniteQueryOptions({ + queryKey: createKey(), + initialPageParam: 0, + queryFn: ({ pageParam }) => Promise.resolve(pageParam), + getNextPageParam: () => undefined, + initialData: { pages: [1], pageParams: [0] }, + select: (data) => data.pages.length, + }) + const query = createInfiniteQuery(() => options) + expectTypeOf(query.data).toEqualTypeOf() + }) + it('should not allow excess properties', () => { const key = createKey() assertType( diff --git a/packages/svelte-query/tests/mutationOptions/mutationOptions.test-d.ts b/packages/svelte-query/tests/mutationOptions/mutationOptions.test-d.ts index ff62321669d..30afad8e8d7 100644 --- a/packages/svelte-query/tests/mutationOptions/mutationOptions.test-d.ts +++ b/packages/svelte-query/tests/mutationOptions/mutationOptions.test-d.ts @@ -1,4 +1,7 @@ -import { QueryClient } from '@tanstack/query-core' +import { + QueryClient, + mutationOptions as coreMutationOptions, +} from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' import { assertType, describe, expectTypeOf, it } from 'vitest' import { @@ -184,6 +187,18 @@ describe('mutationOptions', () => { ) }) + it('should work when core mutationOptions are used with createMutation', () => { + const mutation = createMutation(() => + coreMutationOptions({ + mutationFn: (input: { id: string }) => Promise.resolve(input.id), + }), + ) + + expectTypeOf(mutation.data).toEqualTypeOf() + expectTypeOf(mutation.variables).toEqualTypeOf<{ id: string } | undefined>() + expectTypeOf(mutation.mutate).toBeCallableWith({ id: '1' }) + }) + it('should work when used with useIsMutating', () => { const key = createKey() From 1211ecabe7c1e4fa5b147d6f45985861a181465a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjam=C3=ADn=20Vicente?= Date: Thu, 26 Nov 2026 00:15:14 -0300 Subject: [PATCH 2/2] feat(vue-query): accept getters of query-core options --- .changeset/core-query-options.md | 3 +- .../src/__tests__/coreOptions.test-d.ts | 360 ++++++++++++++++++ .../src/__tests__/coreOptions.test.ts | 126 ++++++ packages/vue-query/src/types.ts | 12 + packages/vue-query/src/useBaseQuery.ts | 3 + packages/vue-query/src/useInfiniteQuery.ts | 85 +++++ packages/vue-query/src/useQueries.ts | 3 + packages/vue-query/src/useQuery.ts | 83 +++- packages/vue-query/src/utils.ts | 2 + 9 files changed, 675 insertions(+), 2 deletions(-) create mode 100644 packages/vue-query/src/__tests__/coreOptions.test-d.ts create mode 100644 packages/vue-query/src/__tests__/coreOptions.test.ts diff --git a/.changeset/core-query-options.md b/.changeset/core-query-options.md index 17a0fb90000..215e3ec2eeb 100644 --- a/.changeset/core-query-options.md +++ b/.changeset/core-query-options.md @@ -1,5 +1,6 @@ --- '@tanstack/query-core': minor +'@tanstack/vue-query': minor --- -Add framework-agnostic `queryOptions`, `infiniteQueryOptions`, and `mutationOptions` helpers. They only accept options that every adapter supports, so framework-specific options such as `throwOnError`, `suspense`, and `notifyOnChangeProps` stay in each adapter's helpers. +Add framework-agnostic `queryOptions`, `infiniteQueryOptions`, and `mutationOptions` helpers. They only accept options that every adapter supports, so framework-specific options such as `throwOnError`, `suspense`, and `notifyOnChangeProps` stay in each adapter's helpers. `useQuery` and `useInfiniteQuery` from `@tanstack/vue-query` accept a getter of these options. diff --git a/packages/vue-query/src/__tests__/coreOptions.test-d.ts b/packages/vue-query/src/__tests__/coreOptions.test-d.ts new file mode 100644 index 00000000000..1d182e54b08 --- /dev/null +++ b/packages/vue-query/src/__tests__/coreOptions.test-d.ts @@ -0,0 +1,360 @@ +import { + infiniteQueryOptions as coreInfiniteQueryOptions, + mutationOptions as coreMutationOptions, + queryOptions as coreQueryOptions, + skipToken, +} from '@tanstack/query-core' +import { createKey } from '@tanstack/query-test-utils' +import { assertType, describe, expectTypeOf, it } from 'vitest' +import { ref } from 'vue' +import { QueryClient } from '../queryClient' +import { useInfiniteQuery } from '../useInfiniteQuery' +import { useMutation } from '../useMutation' +import { useQueries } from '../useQueries' +import { useQuery } from '../useQuery' +import type { + CoreQueryOptions, + InfiniteData, + QueryFunctionContext, + QueryKey, +} from '@tanstack/query-core' +import type { Ref } from 'vue' +import type { UseQueryOptions } from '../queryOptions' +import type { MaybeRefOrGetter } from '../types' +import type { UseInfiniteQueryOptions } from '../useInfiniteQuery' + +const queryFn = () => Promise.resolve([1, 2]) +declare const todoId: number + +describe('core options', () => { + describe('useQuery', () => { + it('should accept a getter of core options', () => { + const options = coreQueryOptions({ queryKey: createKey(), queryFn }) + + expectTypeOf(useQuery(() => options).data.value).toEqualTypeOf< + Array | undefined + >() + }) + + it('should accept core options with a tuple key', () => { + const options = coreQueryOptions({ + queryKey: ['todo', 1] as const, + queryFn: ({ queryKey }) => [queryKey[1]], + }) + + expectTypeOf(useQuery(() => options).data.value).toEqualTypeOf< + Array<1> | undefined + >() + }) + + it('should accept core options with query callbacks', () => { + const options = coreQueryOptions({ + queryKey: ['todo', todoId] as const, + queryFn, + enabled: (query) => query.queryKey[1] === todoId, + staleTime: (query) => (query.state.data ? 1000 : 0), + refetchInterval: (query) => (query.state.data ? 1000 : false), + }) + + expectTypeOf(useQuery(() => options).data.value).toEqualTypeOf< + Array | undefined + >() + }) + + it('should infer data from select', () => { + const options = coreQueryOptions({ + queryKey: createKey(), + queryFn, + select: (data) => data.length, + }) + + expectTypeOf(useQuery(() => options).data.value).toEqualTypeOf< + number | undefined + >() + }) + + it('should narrow data when initialData is defined', () => { + const options = coreQueryOptions({ + queryKey: createKey(), + queryFn, + initialData: [1], + }) + + expectTypeOf(useQuery(() => options).data.value).toEqualTypeOf< + Array + >() + }) + + it('should accept skipToken', () => { + const options = coreQueryOptions({ + queryKey: createKey(), + queryFn: Math.random() > 0.5 ? queryFn : skipToken, + }) + + expectTypeOf(useQuery(() => options).data.value).toEqualTypeOf< + Array | undefined + >() + }) + + it('should accept overrides inside the getter', () => { + const enabled = ref(true) + const options = coreQueryOptions({ + queryKey: ['todo', todoId] as const, + queryFn, + enabled: (query) => query.queryKey[1] === todoId, + }) + + expectTypeOf( + useQuery(() => ({ ...options, enabled: enabled.value })).data.value, + ).toEqualTypeOf | undefined>() + }) + + it('should accept generic core options', () => { + function useWrapper(options: CoreQueryOptions) { + return useQuery(() => options) + } + + expectTypeOf(useWrapper).returns.toHaveProperty('data') + }) + + it('should reject invalid overrides of core options', () => { + const options = coreQueryOptions({ queryKey: createKey(), queryFn }) + + assertType( + // @ts-expect-error enabled is not a string + useQuery(() => ({ ...options, enabled: 'yes' })), + ) + assertType( + // @ts-expect-error select receives the query data + useQuery(() => ({ ...options, select: (data: string) => data })), + ) + }) + + it('should reject core options with a ref in the key', () => { + const primitive = coreQueryOptions({ + queryKey: ['todo', ref(1)] as const, + queryFn, + }) + const object = coreQueryOptions({ + queryKey: ['todo', ref({ id: 1 })] as const, + queryFn, + }) + const nested = coreQueryOptions({ + queryKey: ['todo', { ids: [ref(1)] }] as const, + queryFn, + }) + + assertType( + // @ts-expect-error the key contains a ref + useQuery(() => primitive), + ) + assertType( + // @ts-expect-error the key contains a ref + useQuery(() => object), + ) + assertType( + // @ts-expect-error the key contains a ref + useQuery(() => nested), + ) + }) + + it('should accept ref-free keys of any shape', () => { + class TodoId { + constructor(public value: number) {} + } + const queryKey: [string, number?] = ['todo'] + const shapes = coreQueryOptions({ + queryKey: [ + 'todo', + { date: new Date(), map: new Map() }, + new TodoId(1), + ] as const, + queryFn, + }) + const optional = coreQueryOptions({ queryKey, queryFn }) + + expectTypeOf(useQuery(() => shapes).data.value).toEqualTypeOf< + Array | undefined + >() + expectTypeOf(useQuery(() => optional).data.value).toEqualTypeOf< + Array | undefined + >() + }) + + it('should reject callbacks typed with a ref in the key', () => { + const id = ref(1) + type RefKey = readonly ['todo', Ref] + + assertType( + // @ts-expect-error the callback receives the unwrapped key + useQuery(() => ({ + queryKey: ['todo', id] as const, + queryFn: (context: QueryFunctionContext) => + context.queryKey[1].value, + })), + ) + assertType( + useQuery({ + queryKey: ['todo', id] as const, + // @ts-expect-error the callback receives the unwrapped key + queryFn: (context: QueryFunctionContext) => + context.queryKey[1].value, + }), + ) + }) + }) + + describe('useQueries', () => { + it('should infer core options', () => { + const first = coreQueryOptions({ queryKey: createKey(), queryFn }) + const second = coreQueryOptions({ + queryKey: ['todo', todoId] as const, + queryFn: () => Promise.resolve('data'), + enabled: (query) => query.queryKey[1] === todoId, + }) + + const queries = useQueries({ queries: [first, second] }) + + expectTypeOf(queries.value[0].data).toEqualTypeOf< + Array | undefined + >() + expectTypeOf(queries.value[1].data).toEqualTypeOf() + }) + }) + + describe('useInfiniteQuery', () => { + const page = ({ pageParam }: { pageParam: number }) => + Promise.resolve([pageParam]) + const pagination = { + initialPageParam: 0, + getNextPageParam: () => 1, + } + + it('should accept a getter of core options', () => { + const options = coreInfiniteQueryOptions({ + queryKey: createKey(), + queryFn: page, + ...pagination, + enabled: (query) => !query.state.data, + }) + + expectTypeOf(useInfiniteQuery(() => options).data.value).toEqualTypeOf< + InfiniteData> | undefined + >() + }) + + it('should narrow data when initialData is defined', () => { + const options = coreInfiniteQueryOptions({ + queryKey: createKey(), + queryFn: page, + ...pagination, + initialData: { pages: [[1]], pageParams: [0] }, + }) + + expectTypeOf(useInfiniteQuery(() => options).data.value).toEqualTypeOf< + InfiniteData> + >() + }) + }) + + describe('useMutation', () => { + it('should accept core options directly and through a getter', () => { + const options = coreMutationOptions({ + mutationKey: createKey(), + mutationFn: (value: number) => Promise.resolve(String(value)), + }) + + expectTypeOf(useMutation(options).data.value).toEqualTypeOf< + string | undefined + >() + expectTypeOf(useMutation(() => options).data.value).toEqualTypeOf< + string | undefined + >() + useMutation(options).mutate(1) + // @ts-expect-error variables are numbers + useMutation(options).mutate('1') + }) + + it('should keep the lifecycle callback types', () => { + const options = coreMutationOptions({ + mutationFn: (value: number) => Promise.resolve(String(value)), + onMutate: (value) => ({ value }), + onSuccess: (data, variables, onMutateResult) => { + expectTypeOf(data).toEqualTypeOf() + expectTypeOf(variables).toEqualTypeOf() + expectTypeOf(onMutateResult).toEqualTypeOf<{ value: number }>() + }, + }) + + useMutation(options).mutate(1) + }) + + it('should accept reactive overrides of core options', () => { + const options = coreMutationOptions({ + mutationFn: (value: number) => Promise.resolve(String(value)), + }) + + expectTypeOf( + useMutation({ ...options, retry: ref(2) }).data.value, + ).toEqualTypeOf() + expectTypeOf( + useMutation({ ...options, shallow: true }).data.value, + ).toEqualTypeOf() + }) + }) + + describe('queryClient', () => { + it('should accept core options', () => { + const queryClient = new QueryClient() + const query = coreQueryOptions({ queryKey: createKey(), queryFn }) + + assertType>>(queryClient.query(query)) + assertType | undefined>( + queryClient.getQueryData(query.queryKey), + ) + }) + }) + + describe('existing Vue options', () => { + const id = ref(1) + + it('should keep unwrapping ref keys in getters', () => { + useQuery(() => ({ + queryKey: ['todo', id] as const, + queryFn: ({ queryKey }) => { + expectTypeOf(queryKey[1]).toEqualTypeOf() + return 1 + }, + enabled: (query) => { + expectTypeOf(query.queryKey[1]).toEqualTypeOf() + return true + }, + })) + }) + + it('should keep unwrapping ref keys in infinite getters', () => { + useInfiniteQuery(() => ({ + queryKey: ['todo', id] as const, + queryFn: ({ queryKey }) => { + expectTypeOf(queryKey[1]).toEqualTypeOf() + return 1 + }, + initialPageParam: 0, + getNextPageParam: () => 1, + })) + }) + + it('should keep the Vue options as the last overload', () => { + expectTypeOf[0]>().toEqualTypeOf< + MaybeRefOrGetter< + UseQueryOptions + > + >() + expectTypeOf[0]>().toEqualTypeOf< + MaybeRefOrGetter< + UseInfiniteQueryOptions + > + >() + }) + }) +}) diff --git a/packages/vue-query/src/__tests__/coreOptions.test.ts b/packages/vue-query/src/__tests__/coreOptions.test.ts new file mode 100644 index 00000000000..03752d959ad --- /dev/null +++ b/packages/vue-query/src/__tests__/coreOptions.test.ts @@ -0,0 +1,126 @@ +import { + infiniteQueryOptions as coreInfiniteQueryOptions, + mutationOptions as coreMutationOptions, + queryOptions as coreQueryOptions, +} from '@tanstack/query-core' +import { createKey, sleep } from '@tanstack/query-test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { nextTick, ref } from 'vue' +import { useInfiniteQuery } from '../useInfiniteQuery' +import { useMutation } from '../useMutation' +import { useQuery } from '../useQuery' + +vi.mock(import('../useQueryClient')) + +describe('core options', () => { + beforeEach(() => { + vi.useFakeTimers() + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('should fetch with a getter of core options', async () => { + const options = coreQueryOptions({ + queryKey: createKey(), + queryFn: () => sleep(0).then(() => 'data'), + }) + + const { data } = useQuery(() => options) + await vi.advanceTimersByTimeAsync(0) + + expect(data.value).toBe('data') + }) + + it('should pass the query to a core enabled callback', async () => { + const key = createKey() + const enabled = vi.fn< + (query: { queryKey: ReadonlyArray }) => boolean + >((query) => Array.isArray(query.queryKey)) + const options = coreQueryOptions({ + queryKey: key, + queryFn: () => sleep(0).then(() => 'data'), + enabled, + }) + + useQuery(() => options) + await vi.advanceTimersByTimeAsync(0) + + expect(enabled.mock.calls[0]?.[0].queryKey).toStrictEqual(key) + }) + + it('should react to core options selected in a getter', async () => { + const id = ref(1) + const todoOptions = (todoId: number) => + coreQueryOptions({ + queryKey: ['todo', todoId], + queryFn: () => sleep(0).then(() => todoId), + }) + + const { data } = useQuery(() => todoOptions(id.value)) + await vi.advanceTimersByTimeAsync(0) + expect(data.value).toBe(1) + + id.value = 2 + await nextTick() + await vi.advanceTimersByTimeAsync(0) + + expect(data.value).toBe(2) + }) + + it('should let an override in the getter replace a core enabled callback', async () => { + const enabled = ref(false) + const queryFn = vi.fn<() => Promise>(() => + sleep(0).then(() => 'data'), + ) + const options = coreQueryOptions({ + queryKey: createKey(), + queryFn, + enabled: () => true, + }) + + useQuery(() => ({ ...options, enabled: enabled.value })) + await vi.advanceTimersByTimeAsync(0) + expect(queryFn).not.toHaveBeenCalled() + + enabled.value = true + await nextTick() + await vi.advanceTimersByTimeAsync(0) + + expect(queryFn).toHaveBeenCalledTimes(1) + }) + + it('should fetch with a getter of core infinite options', async () => { + const options = coreInfiniteQueryOptions({ + queryKey: createKey(), + queryFn: ({ pageParam }) => sleep(0).then(() => pageParam), + initialPageParam: 0, + getNextPageParam: (lastPage) => lastPage + 1, + }) + + const { data, fetchNextPage } = useInfiniteQuery(() => options) + await vi.advanceTimersByTimeAsync(0) + expect(data.value?.pages).toStrictEqual([0]) + + void fetchNextPage() + await vi.advanceTimersByTimeAsync(0) + + expect(data.value?.pages).toStrictEqual([0, 1]) + }) + + it('should run core mutation options', async () => { + const onSuccess = vi.fn<(data: number, variables: number) => void>() + const options = coreMutationOptions({ + mutationFn: (value: number) => sleep(0).then(() => value + 1), + onSuccess, + }) + + const { mutate, data } = useMutation(options) + mutate(1) + await vi.advanceTimersByTimeAsync(0) + + expect(data.value).toBe(2) + expect(onSuccess.mock.calls[0]?.slice(0, 2)).toStrictEqual([2, 1]) + }) +}) diff --git a/packages/vue-query/src/types.ts b/packages/vue-query/src/types.ts index d677cd0b006..1d3bc75772d 100644 --- a/packages/vue-query/src/types.ts +++ b/packages/vue-query/src/types.ts @@ -83,6 +83,18 @@ export type DeepUnwrapRef = T extends UnwrapLeaf } : UnwrapRef +// Options typed for `@tanstack/query-core` keep the key as written, so their callbacks would be typed with the `ref`, +// but at runtime they receive the unwrapped key. +/** + * Rejects a `queryKey` that contains a `ref`. + * @internal + */ +export type RefFreeQueryKey = [DeepUnwrapRef] extends [ + TQueryKey, +] + ? unknown + : { queryKey?: never } + /** * The `vue-query`-specific `shallow` option, accepted by query and mutation options. */ diff --git a/packages/vue-query/src/useBaseQuery.ts b/packages/vue-query/src/useBaseQuery.ts index 0a4a580e14d..47b8067e851 100644 --- a/packages/vue-query/src/useBaseQuery.ts +++ b/packages/vue-query/src/useBaseQuery.ts @@ -149,6 +149,9 @@ export function useBaseQuery< // A zero-arg function is a Vue getter and must run here so its refs are tracked. // `(query) => boolean` is query-core's callback and is left for core to call. + // The getter's result is cached, so one reading non-reactive state, such as a store from framework-agnostic + // options, is not read again. `(...args)` and `(query = fallback)` have length 0 too, so they don't receive + // the query. Declaring a parameter avoids both. if ( typeof clonedOptions.enabled === 'function' && clonedOptions.enabled.length === 0 diff --git a/packages/vue-query/src/useInfiniteQuery.ts b/packages/vue-query/src/useInfiniteQuery.ts index a8dabafac09..6c9362ccf6c 100644 --- a/packages/vue-query/src/useInfiniteQuery.ts +++ b/packages/vue-query/src/useInfiniteQuery.ts @@ -6,6 +6,7 @@ import type { InfiniteData, InfiniteQueryObserverOptions, InfiniteQueryObserverResult, + NonUndefinedGuard, QueryKey, QueryObserver, } from '@tanstack/query-core' @@ -20,6 +21,7 @@ import type { MaybeRef, MaybeRefDeep, MaybeRefOrGetter, + RefFreeQueryKey, ShallowOption, } from './types' import type { UseBaseQueryReturnType } from './useBaseQuery' @@ -377,6 +379,89 @@ export function useInfiniteQuery< queryClient?: QueryClient, ): UseInfiniteQueryReturnType +// The `@tanstack/query-core` overloads come after the Vue overloads, so that options those accept resolve exactly as +// before. +/** + * Accepts a getter returning options from `@tanstack/query-core`, such as those created by its `queryOptions` + * helper. This overload is selected when `initialData` is known to be defined. + * @param options - A getter returning the options from `@tanstack/query-core` to use. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin` + * will be used. + * @returns The current infinite query result, typed so that `data` is never `undefined` (unless a `select` + * changes `TData` to include `undefined`). + */ +export function useInfiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: () => InfiniteQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + > & + RefFreeQueryKey & { + initialData: + | NonUndefinedGuard> + | (() => NonUndefinedGuard>) + }, + queryClient?: QueryClient, +): UseInfiniteQueryDefinedReturnType + +/** + * Accepts a getter returning options from `@tanstack/query-core`, such as those created by its `queryOptions` + * helper. + * @param options - A getter returning the options from `@tanstack/query-core` to use. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin` + * will be used. + * @returns The current infinite query result, with `data` typed as possibly `undefined`. + */ +export function useInfiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: () => InfiniteQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + > & + RefFreeQueryKey, + queryClient?: QueryClient, +): UseInfiniteQueryReturnType + +// Repeats the Vue fallback overload: `Parameters` reads the last overload, so it has to stay +// `UseInfiniteQueryOptions`. +/** + * Fallback overload for options whose `initialData` presence isn't statically known, with `data` typed as possibly + * `undefined`. + * @param options - A `ref`, plain value, or reactive getter resolving to the {@link UseInfiniteQueryOptions} to + * use. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin` + * will be used. + * @returns The current infinite query result, with `data` typed as possibly `undefined`. + */ +export function useInfiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: MaybeRefOrGetter< + UseInfiniteQueryOptions + >, + queryClient?: QueryClient, +): UseInfiniteQueryReturnType + export function useInfiniteQuery( options: MaybeRefOrGetter, queryClient?: QueryClient, diff --git a/packages/vue-query/src/useQueries.ts b/packages/vue-query/src/useQueries.ts index a5df7bb9ecb..493926d68aa 100644 --- a/packages/vue-query/src/useQueries.ts +++ b/packages/vue-query/src/useQueries.ts @@ -394,6 +394,9 @@ export function useQueries< // A zero-arg function is a Vue getter and must run here so its refs are tracked. // `(query) => boolean` is query-core's callback and is left for core to call. + // The getter's result is cached, so one reading non-reactive state, such as a store from framework-agnostic + // options, is not read again. `(...args)` and `(query = fallback)` have length 0 too, so they don't receive + // the query. Declaring a parameter avoids both. if ( typeof clonedOptions.enabled === 'function' && clonedOptions.enabled.length === 0 diff --git a/packages/vue-query/src/useQuery.ts b/packages/vue-query/src/useQuery.ts index 51caa42222e..228c300052f 100644 --- a/packages/vue-query/src/useQuery.ts +++ b/packages/vue-query/src/useQuery.ts @@ -3,7 +3,9 @@ import { useBaseQuery } from './useBaseQuery' import type { DefaultError, DefinedQueryObserverResult, + NonUndefinedGuard, QueryKey, + QueryObserverOptions, } from '@tanstack/query-core' import type { QueryClient } from './queryClient' import type { @@ -11,7 +13,7 @@ import type { UndefinedInitialQueryOptions, UseQueryOptions, } from './queryOptions' -import type { MaybeRefOrGetter } from './types' +import type { MaybeRefOrGetter, RefFreeQueryKey } from './types' import type { UseBaseQueryReturnType } from './useBaseQuery' /** @@ -329,6 +331,85 @@ export function useQuery< queryClient?: QueryClient, ): UseQueryReturnType +// The `@tanstack/query-core` overloads come after the Vue overloads, so that options those accept resolve exactly as +// before. +/** + * Accepts a getter returning options from `@tanstack/query-core`, such as those created by its `queryOptions` + * helper. This overload is selected when `initialData` is known to be defined. + * @param options - A getter returning the options from `@tanstack/query-core` to use. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin` + * will be used. + * @returns The current query result, typed so that `data` is never `undefined` (unless a `select` changes + * `TData` to include `undefined`). + */ +export function useQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: () => QueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryFnData, + TQueryKey + > & + RefFreeQueryKey & { + initialData: + | NonUndefinedGuard + | (() => NonUndefinedGuard) + }, + queryClient?: QueryClient, +): UseQueryDefinedReturnType + +/** + * Accepts a getter returning options from `@tanstack/query-core`, such as those created by its `queryOptions` + * helper. + * @param options - A getter returning the options from `@tanstack/query-core` to use. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin` + * will be used. + * @returns The current query result, with `data` typed as possibly `undefined`. + */ +export function useQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: () => QueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryFnData, + TQueryKey + > & + RefFreeQueryKey, + queryClient?: QueryClient, +): UseQueryReturnType + +// Repeats the Vue fallback overload: `Parameters` reads the last overload, so it has to stay +// `UseQueryOptions`. +/** + * Fallback overload for options whose `initialData` presence isn't statically known, with `data` typed as possibly + * `undefined`. + * @param options - A `ref`, plain value, or reactive getter resolving to the {@link UseQueryOptions} to use. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin` + * will be used. + * @returns The current query result, with `data` typed as possibly `undefined`. + */ +export function useQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: MaybeRefOrGetter< + UseQueryOptions + >, + queryClient?: QueryClient, +): UseQueryReturnType + export function useQuery< TQueryFnData, TError = DefaultError, diff --git a/packages/vue-query/src/utils.ts b/packages/vue-query/src/utils.ts index c87bc40eca2..bd0ab315615 100644 --- a/packages/vue-query/src/utils.ts +++ b/packages/vue-query/src/utils.ts @@ -69,6 +69,8 @@ function _cloneDeep( ) as unknown as T } + // Every plain object is walked, including `initialData`, `placeholderData` and `meta`. A cyclic one overflows the + // stack, and `Object.entries` skips symbol keys. if (typeof value === 'object' && isPlainObject(value)) { const entries = Object.entries(value as Record).map( ([key, val]) => [key, _cloneDeep(val, customize, key, currentLevel + 1)],