@kubb/plugin-vue-query 5.10.3 → 5.10.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,64 +1,48 @@
1
1
  # Call operations
2
2
 
3
- `@kubb/plugin-vue-query` can generate a typed TanStack Query composable for each operation. `GET` operations get query composables such as `useGetPetById`, and `POST`, `PUT`, `PATCH`, and `DELETE` operations get mutation composables such as `useUpdatePetWithForm`. Each composable calls the client function from `@kubb/plugin-fetch`, `@kubb/plugin-axios`, or `@kubb/plugin-client`.
3
+ Use the generated TanStack Query composables and factories in Vue: queries, mutations, and infinite lists with reactive parameters.
4
4
 
5
- > [!IMPORTANT]
6
- > By default the plugin emits only the factory helpers (`queryOptions`, `queryKey`, `mutationKey`). Set [`hooks: true`](https://kubb.dev/extensions/kubb-labs/plugin-vue-query/options#hooks) in the plugin options to also generate the `use*` composables shown below.
5
+ ## What each plugin generates
7
6
 
8
- ## Queries
7
+ Each composable and its helpers live in a file named after the composable, such as `src/gen/hooks/useGetPetById.ts`.
9
8
 
10
- A query composable takes grouped request parameters as its first argument. Parameters accept a value, ref, or getter. See [reactive parameters](#refetch-when-parameters-change).
9
+ | Operation | Exports |
10
+ | ------------------------------------------- | --------------------------------------------------------------------------------------------------- |
11
+ | Query (`GET`, `QUERY`) | `getPetByIdQueryKey`, `getPetByIdQueryOptions`, plus `useGetPetById` with `hooks` |
12
+ | Mutation (`POST`, `PUT`, `PATCH`, `DELETE`) | `updatePetMutationKey`, plus `useUpdatePet` with `hooks` |
13
+ | Infinite, with `infinite` and `hooks` | `findPetsByTagsInfiniteQueryKey`, `findPetsByTagsInfiniteQueryOptions`, `useFindPetsByTagsInfinite` |
14
+ | Server-Sent Events or JSON Lines | Nothing. Call the client function directly. |
11
15
 
12
- ```typescript [usage.ts]
13
- import { useGetPetById } from './gen/hooks/useGetPetById'
16
+ ## Call a composable
14
17
 
15
- const { data, error, isLoading } = useGetPetById({ path: { petId: 1 } })
16
- ```
18
+ The examples set `hooks: true`, and [`integerType: 'number'`](https://kubb.dev/extensions/kubb-labs/adapter-oas/options#integertype) on the adapter so `petId` is a `number`. Path keys keep their spec names unless you set [`pathParamsCasing`](https://kubb.dev/extensions/kubb-labs/adapter-oas/options#pathparamscasing).
17
19
 
18
- The examples set [`integerType: 'number'`](https://kubb.dev/extensions/kubb-labs/adapter-oas/options#integertype) on the adapter, so an `int64` id such as `petId` is a `number`. With the default it is a `bigint` and the call takes `1n`.
20
+ ::tabs
19
21
 
20
- Path keys keep the names from the spec, so a `{pet-id}` placeholder is passed as `path: { 'pet-id': 1 }`. Set [`pathParamsCasing: 'camelcase'`](https://kubb.dev/extensions/kubb-labs/adapter-oas/options#pathparamscasing) on the adapter (`@kubb/adapter-oas` 5.20.0 or later) to pass `path: { petId: 1 }` instead, the name MSW handlers and query keys already use. The HTTP request stays the same.
22
+ :::tabs-item{label="Query"}
21
23
 
22
- The second argument has two optional groups. `query` takes any TanStack Query option, and `query.client` sets the `QueryClient` to use. The top-level `client` takes request config for this call, such as `baseURL`:
24
+ The first argument takes the request groups (`path`, `query`, `headers`), each as a value, a ref, or a getter. The second takes TanStack Query options in `query`, with `query.client` for the `QueryClient`, and request config such as `baseURL` in `client`.
23
25
 
24
26
  ```typescript
25
27
  import { useFindPetsByTags } from './gen/hooks/useFindPetsByTags'
26
28
 
27
- useFindPetsByTags(
29
+ const { data, error, isLoading } = useFindPetsByTags(
28
30
  { query: { tags: ['dog'] } },
29
- {
30
- query: { staleTime: 60_000 },
31
- client: { baseURL: 'https://api.example.com/v1' },
32
- },
31
+ { query: { staleTime: 60_000 }, client: { baseURL: 'https://api.example.com/v1' } },
33
32
  )
34
33
  ```
35
34
 
36
- ## Factories
37
-
38
- Every query operation also exports a `queryOptions` factory and a `queryKey` helper for prefetching and invalidation. The key is `[{ url }, query]`, built from the operation path and its query params:
39
-
40
- ```typescript
41
- import { useQueryClient } from '@tanstack/vue-query'
42
- import { findPetsByTagsQueryKey, findPetsByTagsQueryOptions } from './gen/hooks/useFindPetsByTags'
43
-
44
- const queryClient = useQueryClient()
45
-
46
- await queryClient.prefetchQuery(findPetsByTagsQueryOptions({ query: { tags: ['dog'] } }))
47
- queryClient.invalidateQueries({ queryKey: findPetsByTagsQueryKey({ query: { tags: ['dog'] } }) })
48
- ```
49
-
50
- Mutations export a `mutationKey` helper next to the composable.
35
+ :::
51
36
 
52
- ## Mutations
37
+ :::tabs-item{label="Mutation"}
53
38
 
54
- A mutation composable takes only an options object. The grouped request config is the mutation variable, so you pass it to `mutate` or `mutateAsync`:
39
+ A mutation composable takes only the options object, with `mutation` and `client`. Pass the request groups to `mutate` or `mutateAsync`.
55
40
 
56
41
  ```typescript
57
42
  import { useQueryClient } from '@tanstack/vue-query'
58
43
  import { useUpdatePetWithForm } from './gen/hooks/useUpdatePetWithForm'
59
44
 
60
45
  const queryClient = useQueryClient()
61
-
62
46
  const { mutate } = useUpdatePetWithForm({
63
47
  mutation: { onSuccess: () => queryClient.invalidateQueries() },
64
48
  })
@@ -66,70 +50,59 @@ const { mutate } = useUpdatePetWithForm({
66
50
  mutate({ path: { petId: 1 }, query: { name: 'Fluffy' } })
67
51
  ```
68
52
 
69
- ## Errors and transport
70
-
71
- Each generated composable calls the client function with `throwOnError: true`. A failed request sets TanStack Query's `error`, typed from the error responses in the spec. Set the base URL, authentication, interceptors, serialization, and validation on the client plugin. See the [plugin-fetch](https://kubb.dev/extensions/kubb-labs/plugin-fetch) or [plugin-axios](https://kubb.dev/extensions/kubb-labs/plugin-axios) guide. With [plugin-client](https://kubb.dev/extensions/kubb-labs/plugin-client), set these in your own client module.
72
-
73
- ## Customize cache keys
74
-
75
- Set `queryKey` on the plugin to change generated keys. String entries are emitted as source code, so use `JSON.stringify` for a string literal.
76
-
77
- ```typescript [kubb.config.ts]
78
- import { pluginVueQuery } from '@kubb/plugin-vue-query'
79
-
80
- pluginVueQuery({
81
- queryKey: ({ node }) => [JSON.stringify(node.operationId)],
82
- })
83
- ```
84
-
85
- > [!WARNING]
86
- > This `queryKey` gives every call the same key, such as `['getUserByName']`. If path or query values select different data, add them to the key.
87
-
88
- ## Load more pages
53
+ :::
89
54
 
90
- Configure `infinite` with a query parameter declared by the operation, its initial value, and the response path for the next cursor. Infinite output needs `hooks: true`, and only operations that declare the `queryParam` receive it.
55
+ :::tabs-item{label="Infinite"}
91
56
 
92
- ::code-group
57
+ Only operations that declare `infinite.queryParam` get an infinite composable. Point `nextParam` at the cursor in the response, and give `initialPageParam` the type of the query parameter. See [Infinite queries](https://kubb.dev/extensions/kubb-labs/plugin-vue-query/guides/infinite-queries).
93
58
 
94
59
  ```typescript [kubb.config.ts]
95
- import { pluginVueQuery } from '@kubb/plugin-vue-query'
96
-
97
60
  pluginVueQuery({
98
61
  hooks: true,
99
- infinite: {
100
- queryParam: 'page',
101
- initialPageParam: 0,
102
- nextParam: 'pagination.next.cursor',
103
- },
62
+ infinite: { queryParam: 'page', initialPageParam: 0, nextParam: 'pagination.next.cursor' },
104
63
  })
105
64
  ```
106
65
 
107
- ```typescript [usage.ts]
66
+ ```typescript
108
67
  import { useFindPetsByTagsInfinite } from './gen/hooks/useFindPetsByTagsInfinite'
109
68
 
110
- const { data, fetchNextPage, hasNextPage } = useFindPetsByTagsInfinite({
111
- query: () => ({ tags: ['dog'] }),
112
- })
69
+ const { data, fetchNextPage, hasNextPage } = useFindPetsByTagsInfinite({ query: () => ({ tags: ['dog'] }) })
113
70
  ```
114
71
 
115
- ::
72
+ :::
116
73
 
117
- `nextParam` takes dot notation or an array of keys. Change it to match your API's response, and give `initialPageParam` the same type as the query parameter. Without `getNextPageParam`, `nextParam` or `cursorParam`, the generated options increment the page number until a page returns an empty array.
74
+ ::
118
75
 
119
76
  ## Refetch when parameters change
120
77
 
121
- Enable `hooks: true`, then pass a ref or getter to a generated composable. Parameters accept `MaybeRefOrGetter`. A getter tracks its reactive dependencies.
78
+ Pass a ref or a getter instead of a value. A change updates the query key and fetches again:
122
79
 
123
- ```typescript [usage.ts]
80
+ ```typescript
124
81
  import { ref } from 'vue'
125
82
  import { useFindPetsByTags } from './gen/hooks/useFindPetsByTags'
126
83
 
127
84
  const tags = ref(['dog'])
128
- const { data, error, isLoading } = useFindPetsByTags({
129
- query: () => ({ tags: tags.value }),
130
- })
85
+ const { data } = useFindPetsByTags({ query: () => ({ tags: tags.value }) })
86
+
87
+ tags.value = ['cat'] // fetches the cat list
88
+ ```
89
+
90
+ ## Prefetch and invalidate
91
+
92
+ The factories work without `hooks`, so you can prefetch or invalidate outside a component:
93
+
94
+ ```typescript
95
+ import { findPetsByTagsQueryKey, findPetsByTagsQueryOptions } from './gen/hooks/useFindPetsByTags'
96
+ import { queryClient } from './queryClient' // the QueryClient you pass to VueQueryPlugin
131
97
 
132
- tags.value = ['cat']
98
+ await queryClient.prefetchQuery(findPetsByTagsQueryOptions({ query: { tags: ['dog'] } }))
99
+ queryClient.invalidateQueries({ queryKey: findPetsByTagsQueryKey({ query: { tags: ['dog'] } }) })
133
100
  ```
134
101
 
135
- Changing `tags.value` updates the query key and fetches the corresponding resource.
102
+ [TanStack Query keys](https://kubb.dev/extensions/kubb-labs/plugin-vue-query/guides/query-keys) shows the default keys. To change them, set [`queryKey`](https://kubb.dev/extensions/kubb-labs/plugin-vue-query/options#querykey) and [`mutationKey`](https://kubb.dev/extensions/kubb-labs/plugin-vue-query/options#mutationkey).
103
+
104
+ ## Handle errors
105
+
106
+ Each composable calls the client with `throwOnError: true`, so a failed request sets TanStack Query's `error`, typed from the spec's error responses.
107
+
108
+ Next, set the base URL, auth, and interceptors on your client plugin: [plugin-fetch](https://kubb.dev/extensions/kubb-labs/plugin-fetch), [plugin-axios](https://kubb.dev/extensions/kubb-labs/plugin-axios), or your own module with [plugin-client](https://kubb.dev/extensions/kubb-labs/plugin-client/guides/write-your-client).
@@ -0,0 +1,88 @@
1
+ # Infinite queries with useInfiniteQuery
2
+
3
+ Generate `useInfiniteQuery` composables for paginated endpoints, read the next cursor from the response, and stop once the last page arrives.
4
+
5
+ ## Generate infinite composables
6
+
7
+ When an endpoint pages through results with a query parameter, set [`infinite`](https://kubb.dev/extensions/kubb-labs/plugin-vue-query/options#infinite) next to `hooks: true`. Only operations that declare `infinite.queryParam` get an infinite composable, and the composable sends each page param as that parameter:
8
+
9
+ ::code-group
10
+
11
+ ```typescript [kubb.config.ts]
12
+ import { defineConfig } from 'kubb/config'
13
+ import { pluginTs } from '@kubb/plugin-ts'
14
+ import { pluginFetch } from '@kubb/plugin-fetch'
15
+ import { pluginVueQuery } from '@kubb/plugin-vue-query'
16
+
17
+ export default defineConfig({
18
+ input: './petStore.yaml',
19
+ output: { path: './src/gen' },
20
+ plugins: [
21
+ pluginTs(),
22
+ pluginFetch(),
23
+ pluginVueQuery({
24
+ hooks: true,
25
+ infinite: { queryParam: 'page', initialPageParam: 0, nextParam: 'pagination.next.cursor' },
26
+ }),
27
+ ],
28
+ })
29
+ ```
30
+
31
+ ```typescript [Generated]
32
+ // src/gen/hooks/useFindPetsByTagsInfinite.ts, types left out
33
+ export const findPetsByTagsInfiniteQueryKey = ({ query }: { query?: MaybeRefOrGetter<Omit<FindPetsByTagsOptions, 'headers'>['query']> } = {}) =>
34
+ [{ url: '/pet/findByTags', infinite: true }, ...(query ? [query] : [])] as const
35
+
36
+ export function findPetsByTagsInfiniteQueryOptions({ query }: { query?: MaybeRefOrGetter<FindPetsByTagsOptions['query']> } = {}, config = {}) {
37
+ const queryKey = findPetsByTagsInfiniteQueryKey({ query })
38
+ return infiniteQueryOptions({
39
+ queryKey,
40
+ queryFn: async ({ signal, pageParam }) => {
41
+ return findPetsByTags({ ...config, query: { ...toValue(query), page: pageParam }, signal: config.signal ?? signal, throwOnError: true }).unwrap()
42
+ },
43
+ initialPageParam: 0,
44
+ getNextPageParam: (lastPage) => lastPage?.['pagination']?.['next']?.['cursor'],
45
+ })
46
+ }
47
+ ```
48
+
49
+ ```typescript [Usage]
50
+ import { ref } from 'vue'
51
+ import { useFindPetsByTagsInfinite } from './gen/hooks/useFindPetsByTagsInfinite'
52
+
53
+ const tags = ref(['dog'])
54
+ const { data, fetchNextPage, hasNextPage } = useFindPetsByTagsInfinite({ query: () => ({ tags: tags.value }) })
55
+ ```
56
+
57
+ ::
58
+
59
+ - Give `initialPageParam` the type of the query parameter.
60
+ - The infinite key adds `infinite: true`, so it never shares a cache entry with the plain query. See [TanStack Query keys](https://kubb.dev/extensions/kubb-labs/plugin-vue-query/guides/query-keys).
61
+ - A ref or getter in `query` updates the key, so a change starts again from the first page.
62
+
63
+ ## Read the next page from the response
64
+
65
+ The generated `getNextPageParam` comes from the first of these options you set:
66
+
67
+ | Option | Generated `getNextPageParam` |
68
+ | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
69
+ | [`getNextPageParam`](https://kubb.dev/extensions/kubb-labs/plugin-vue-query/options#infinitegetnextpageparam) | Your function's source, copied as written. It cannot use variables from the config file. |
70
+ | [`nextParam`](https://kubb.dev/extensions/kubb-labs/plugin-vue-query/options#infinitenextparam) | Reads that path on the last page, such as `lastPage?.['pagination']?.['next']?.['cursor']`. |
71
+ | [`cursorParam`](https://kubb.dev/extensions/kubb-labs/plugin-vue-query/options#infinitecursorparam) | Deprecated. Reads that top-level field. |
72
+ | None | Counts pages up from `initialPageParam` until a page is an empty array. |
73
+
74
+ `getPreviousPageParam`, `previousParam`, and `cursorParam` set the previous page in the same order. With [`returnType: 'full'`](https://kubb.dev/extensions/kubb-labs/plugin-vue-query/options#returntype), the `nextParam` and `cursorParam` accessors read from `lastPage.data`.
75
+
76
+ ## hasNextPage never turns false
77
+
78
+ Generation prints this warning for the operation:
79
+
80
+ ```text
81
+ findPetsByTags: the default infinite page params expect an array response and never end for this one. Set `infinite.getNextPageParam` (or `nextParam`) to read the next page from the response.
82
+ ```
83
+
84
+ Without `getNextPageParam`, `nextParam`, or `cursorParam`, the composable counts pages up from `initialPageParam` until a page is an empty array. That works only for array responses, so generation warns for any other response. It skips the warning when `previousParam` or `getPreviousPageParam` is set, though the count still never ends.
85
+
86
+ To fix it, set `nextParam` to the cursor path, or `getNextPageParam` when you must compute the next page.
87
+
88
+ Next, see every [`infinite` option](https://kubb.dev/extensions/kubb-labs/plugin-vue-query/options#infinite), including `definePageParam` for a typed `getNextPageParam`.
@@ -0,0 +1,113 @@
1
+ # TanStack Query keys
2
+
3
+ See the query key each generated Vue Query composable uses, invalidate or read the cache with it, and add your own prefix to the default key.
4
+
5
+ ## The default query key
6
+
7
+ When you call `invalidateQueries`, `getQueryData`, or `setQueryData`, take the key from the `<operation>QueryKey` helper in each composable file. It builds `[{ url, params }, query, body]`:
8
+
9
+ ::code-group
10
+
11
+ ```typescript [Generated]
12
+ // src/gen/hooks/useGetPetById.ts
13
+ export const getPetByIdQueryKey = ({ path }: { path: MaybeRefOrGetter<Omit<GetPetByIdOptions, 'headers'>['path']> }) =>
14
+ [{ url: '/pet/:petId', params: path }] as const
15
+
16
+ // src/gen/hooks/useFindPetsByTags.ts
17
+ export const findPetsByTagsQueryKey = ({ query }: { query?: MaybeRefOrGetter<Omit<FindPetsByTagsOptions, 'headers'>['query']> } = {}) =>
18
+ [{ url: '/pet/findByTags' }, ...(query ? [query] : [])] as const
19
+ ```
20
+
21
+ ```typescript [Usage]
22
+ import { getPetByIdQueryKey } from './gen/hooks/useGetPetById'
23
+ import { findPetsByTagsQueryKey } from './gen/hooks/useFindPetsByTags'
24
+ import { queryClient } from './queryClient'
25
+
26
+ getPetByIdQueryKey({ path: { petId: 1 } }) // [{ url: '/pet/:petId', params: { petId: 1 } }]
27
+ findPetsByTagsQueryKey({ query: { tags: ['dog'] } }) // [{ url: '/pet/findByTags' }, { tags: ['dog'] }]
28
+
29
+ const pet = queryClient.getQueryData(getPetByIdQueryKey({ path: { petId: 1 } }))
30
+ ```
31
+
32
+ ::
33
+
34
+ - `url` is the spec path with `:name` placeholders, such as `'/pet/:petId'`.
35
+ - `params` holds the path parameters, when the path has any.
36
+ - `query` and `body` follow when the operation has them and the call passes them.
37
+ - Headers and cookies stay out of the key.
38
+ - Infinite variants add `infinite: true` to the first entry, so they never share a cache entry with the plain query.
39
+ - Each composable returns the key it used as `queryKey` on its result.
40
+
41
+ ## Keys with refs and getters
42
+
43
+ When you pass a ref or a getter to a composable, the key holds it as passed. Vue Query unwraps refs and getters inside `queryKey`, so a change updates the key and fetches again.
44
+
45
+ > [!NOTE]
46
+ > `getQueryData` and `setQueryData` take the key array itself and do not unwrap getters. Pass plain values or refs to the key helper there.
47
+
48
+ ## Invalidate every call of an operation
49
+
50
+ TanStack Query matches a key by its prefix, and an object entry by the fields you pass. A key built without `query` matches every cached call of that operation with the same path parameters, infinite ones included:
51
+
52
+ ```typescript
53
+ queryClient.invalidateQueries({ queryKey: findPetsByTagsQueryKey() })
54
+ ```
55
+
56
+ ## Mutation keys
57
+
58
+ Each mutation gets a `<operation>MutationKey` helper that returns `[{ url }]`, for filters such as `useIsMutating` or `useMutationState`:
59
+
60
+ ::code-group
61
+
62
+ ```typescript [Generated]
63
+ // src/gen/hooks/useUpdatePet.ts
64
+ export const updatePetMutationKey = () => [{ url: '/pet' }] as const
65
+ ```
66
+
67
+ ```typescript [Usage]
68
+ import { useIsMutating } from '@tanstack/vue-query'
69
+ import { updatePetMutationKey } from './gen/hooks/useUpdatePet'
70
+
71
+ const saving = useIsMutating({ mutationKey: updatePetMutationKey() })
72
+ ```
73
+
74
+ ::
75
+
76
+ ## Extend the default key
77
+
78
+ When you need your own entry, such as an API version, set [`queryKey`](https://kubb.dev/extensions/kubb-labs/plugin-vue-query/options#querykey) and spread `queryKeyTransformer`. Do not read single entries of its result: they can change between releases.
79
+
80
+ > [!WARNING]
81
+ > Returned strings are copied into the generated code as written. Wrap a string literal in `JSON.stringify(...)`.
82
+
83
+ ::code-group
84
+
85
+ ```typescript [kubb.config.ts]
86
+ import { defineConfig } from 'kubb/config'
87
+ import { pluginTs } from '@kubb/plugin-ts'
88
+ import { pluginFetch } from '@kubb/plugin-fetch'
89
+ import { pluginVueQuery, queryKeyTransformer } from '@kubb/plugin-vue-query'
90
+
91
+ export default defineConfig({
92
+ input: './petStore.yaml',
93
+ output: { path: './src/gen' },
94
+ plugins: [
95
+ pluginTs(),
96
+ pluginFetch(),
97
+ pluginVueQuery({
98
+ queryKey: (props) => [JSON.stringify('v2'), ...queryKeyTransformer(props)],
99
+ }),
100
+ ],
101
+ })
102
+ ```
103
+
104
+ ```typescript [Generated]
105
+ export const getPetByIdQueryKey = ({ path }: { path: MaybeRefOrGetter<Omit<GetPetByIdOptions, 'headers'>['path']> }) =>
106
+ ["v2", { url: '/pet/:petId', params: path }] as const
107
+ ```
108
+
109
+ ::
110
+
111
+ The builder also gets the `variant`, so it can return a different key for infinite composables. [`mutationKey`](https://kubb.dev/extensions/kubb-labs/plugin-vue-query/options#mutationkey) works the same way with `mutationKeyTransformer`.
112
+
113
+ Next, [generate infinite queries](https://kubb.dev/extensions/kubb-labs/plugin-vue-query/guides/infinite-queries) for paginated endpoints.