@kubb/plugin-swr 5.9.2 → 5.9.4

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.
package/dist/index.cjs CHANGED
@@ -31,11 +31,11 @@ let _kubb_renderer_jsx = require("@kubb/renderer-jsx");
31
31
  let _kubb_renderer_jsx_jsx_runtime = require("@kubb/renderer-jsx/jsx-runtime");
32
32
  // kubb-extension.json
33
33
  var compatibility = {
34
- "kubb": ">=5.18.4",
34
+ "kubb": ">=5.19.0",
35
35
  "node": ">=22.22"
36
36
  };
37
37
  // package.json
38
- var version = "5.9.2";
38
+ var version = "5.9.4";
39
39
  // ../../internals/client/src/resolveClient.ts
40
40
  /**
41
41
  * Resolves which client plugin a consumer (react-query, vue-query, swr, mcp) should call for an
package/dist/index.js CHANGED
@@ -5,11 +5,11 @@ import { File, Function, Type, jsxRenderer } from "@kubb/renderer-jsx";
5
5
  import { Fragment, jsx, jsxs } from "@kubb/renderer-jsx/jsx-runtime";
6
6
  // kubb-extension.json
7
7
  var compatibility = {
8
- "kubb": ">=5.18.4",
8
+ "kubb": ">=5.19.0",
9
9
  "node": ">=22.22"
10
10
  };
11
11
  // package.json
12
- var version = "5.9.2";
12
+ var version = "5.9.4";
13
13
  // ../../internals/client/src/resolveClient.ts
14
14
  /**
15
15
  * Resolves which client plugin a consumer (react-query, vue-query, swr, mcp) should call for an
@@ -1,40 +1,42 @@
1
1
  # Call operations
2
2
 
3
- `@kubb/plugin-swr` generates a typed SWR hook for each operation. `GET` operations get `useSWR` hooks such as `useGetPetById`, and `POST`, `PUT`, `PATCH`, and `DELETE` operations get `useSWRMutation` hooks such as `useCreatePet`. Each hook calls the client function from `@kubb/plugin-fetch`, `@kubb/plugin-axios`, or `@kubb/plugin-client`.
3
+ Use the generated `useSWR` and `useSWRMutation` hooks, and skip or freeze a request with the Kubb options.
4
4
 
5
- ## Queries
5
+ ## What each plugin generates
6
6
 
7
- A query hook takes the operation's grouped request config (`path`, `query`, `headers`, whichever the operation declares) as its first argument:
7
+ Each hook and its helpers live in a file named after the hook, such as `src/gen/hooks/useGetPetById.ts`.
8
8
 
9
- ```typescript
10
- import { useGetPetById } from './gen/hooks/useGetPetById'
9
+ | Operation | Exports |
10
+ | ------------------------------------------- | --------------------------------------------------------------- |
11
+ | Query (`GET`, `QUERY`) | `getPetByIdQueryKey`, `getPetByIdQueryOptions`, `useGetPetById` |
12
+ | Mutation (`POST`, `PUT`, `PATCH`, `DELETE`) | `updatePetMutationKey`, `useUpdatePet` |
13
+ | Infinite or suspense | Not generated |
14
+ | Server-Sent Events or JSON Lines | Nothing. Call the client function directly. |
11
15
 
12
- const { data, error, isLoading } = useGetPetById({ path: { petId: 1 } })
13
- ```
16
+ ## Call a hook
14
17
 
15
- 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`.
18
+ The examples set [`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).
16
19
 
17
- 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.
20
+ ::tabs
18
21
 
19
- The second argument takes `query` (any `SWRConfiguration`), `client` (request config for this call, such as `baseURL`), and the Kubb options `shouldFetch` and `immutable`, covered in [Skip requests until ready](#skip-requests-until-ready) and [Fetch immutable data](#fetch-immutable-data):
22
+ :::tabs-item{label="Query"}
23
+
24
+ The first argument takes the request groups: `path`, `query`, `headers`. The second takes SWR options (`SWRConfiguration`) in `query`, request config such as `baseURL` in `client`, and the Kubb options `shouldFetch` and `immutable`.
20
25
 
21
26
  ```typescript
22
27
  import { useGetPetById } from './gen/hooks/useGetPetById'
23
28
 
24
- useGetPetById(
29
+ const { data, error, isLoading } = useGetPetById(
25
30
  { path: { petId: 1 } },
26
- {
27
- query: { refreshInterval: 30_000 },
28
- client: { baseURL: 'https://api.example.com/v1' },
29
- },
31
+ { query: { refreshInterval: 30_000 }, client: { baseURL: 'https://api.example.com/v1' } },
30
32
  )
31
33
  ```
32
34
 
33
- The exported `queryKey` helper includes the operation URL and request parameters. Pass it to SWR's `mutate` to update or revalidate that entry.
35
+ :::
34
36
 
35
- ## Mutations
37
+ :::tabs-item{label="Mutation"}
36
38
 
37
- A mutation hook takes only an options object. Pass the grouped request config to `trigger(...)`:
39
+ A mutation hook takes only the options object, with `mutation`, `client`, and `shouldFetch`. Pass the request groups to `trigger`.
38
40
 
39
41
  ```typescript
40
42
  import { mutate } from 'swr'
@@ -48,38 +50,34 @@ const { trigger, isMutating } = useCreatePet({
48
50
  await trigger({ body: { name: 'Fluffy' } })
49
51
  ```
50
52
 
51
- A `mutationKey` helper is exported next to the hook.
53
+ :::
52
54
 
53
- ## Errors and transport
55
+ ::
54
56
 
55
- Each generated hook calls the client function with `throwOnError: true`. A failed request sets SWR'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.
57
+ Pass a `queryKey` helper to SWR's `mutate` to update or revalidate that entry. [SWR keys](https://kubb.dev/extensions/kubb-labs/plugin-swr/guides/query-keys) shows the default keys. To change them, set [`queryKey`](https://kubb.dev/extensions/kubb-labs/plugin-swr/options#querykey) and [`mutationKey`](https://kubb.dev/extensions/kubb-labs/plugin-swr/options#mutationkey).
56
58
 
57
59
  ## Skip requests until ready
58
60
 
59
- Set `shouldFetch: false` to give SWR a `null` key and skip the request. Pass `true` once the required parameters are available. Mutation hooks accept the same option. With a `null` key, calling `trigger` throws a missing-key error.
61
+ `shouldFetch: false` gives SWR a `null` key, so the request waits until you pass `true`. On a mutation hook, `shouldFetch: false` makes `trigger` throw a missing-key error.
60
62
 
61
- ```typescript [usage.ts]
63
+ ```typescript
62
64
  import { useGetPetById } from './gen/hooks/useGetPetById'
63
65
 
64
66
  export function useSelectedPet(petId: number | undefined) {
65
- return useGetPetById(
66
- { path: { petId: petId ?? 0 } },
67
- { shouldFetch: petId != null },
68
- )
67
+ return useGetPetById({ path: { petId: petId ?? 0 } }, { shouldFetch: petId != null })
69
68
  }
70
69
  ```
71
70
 
72
71
  ## Fetch immutable data
73
72
 
74
- Set `immutable: true` on a query hook for data that stays unchanged. It sets `revalidateIfStale`, `revalidateOnFocus`, and `revalidateOnReconnect` to `false`.
75
-
76
- ```typescript [usage.ts]
77
- import { useGetPetById } from './gen/hooks/useGetPetById'
73
+ `immutable: true` on a query hook sets `revalidateIfStale`, `revalidateOnFocus`, and `revalidateOnReconnect` to `false`. Options in `query` still win.
78
74
 
79
- const { data, error } = useGetPetById(
80
- { path: { petId: 1 } },
81
- { immutable: true },
82
- )
75
+ ```typescript
76
+ const { data } = useGetPetById({ path: { petId: 1 } }, { immutable: true })
83
77
  ```
84
78
 
85
- Options in `query` override these revalidation defaults.
79
+ ## Handle errors
80
+
81
+ Each hook calls the client with `throwOnError: true`, so a failed request sets SWR's `error`, typed from the spec's error responses.
82
+
83
+ 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,92 @@
1
+ # SWR keys
2
+
3
+ See the key each generated `useSWR` and `useSWRMutation` hook passes, revalidate with SWR's `mutate`, and add your own prefix to the default key.
4
+
5
+ ## The default key
6
+
7
+ When you call SWR's `mutate`, take the key from the `<operation>QueryKey` helper in each hook file. It builds `[{ url, params }, query, body]`, and the hook passes it to `useSWR`:
8
+
9
+ ::code-group
10
+
11
+ ```typescript [Generated]
12
+ // src/gen/hooks/useGetPetById.ts
13
+ export const getPetByIdQueryKey = ({ path }: Omit<GetPetByIdOptions, 'headers'>) => [{ url: '/pet/:petId', params: path }] as const
14
+
15
+ // inside useGetPetById(), shortened
16
+ const queryKey = getPetByIdQueryKey({ path })
17
+ return useSWR(shouldFetch ? queryKey : null, { ...getPetByIdQueryOptions({ path }, config), ...queryOptions })
18
+ ```
19
+
20
+ ```typescript [Usage]
21
+ import { mutate } from 'swr'
22
+ import { getPetByIdQueryKey } from './gen/hooks/useGetPetById'
23
+
24
+ getPetByIdQueryKey({ path: { petId: 1 } }) // [{ url: '/pet/:petId', params: { petId: 1 } }]
25
+
26
+ await mutate(getPetByIdQueryKey({ path: { petId: 1 } }))
27
+ ```
28
+
29
+ ::
30
+
31
+ - `url` is the spec path with `:name` placeholders, such as `'/pet/:petId'`.
32
+ - `params` holds the path parameters, when the path has any.
33
+ - `query` and `body` follow when the operation has them and the call passes them.
34
+ - Headers and cookies stay out of the key.
35
+ - `shouldFetch: false` passes `null` instead of the key, so SWR skips the request.
36
+
37
+ ## Mutation keys
38
+
39
+ Each mutation gets a `<operation>MutationKey` helper that returns `[{ url }]`. The hook passes it to `useSWRMutation`, or `null` with `shouldFetch: false`:
40
+
41
+ ```typescript [src/gen/hooks/useUpdatePet.ts]
42
+ export const updatePetMutationKey = () => [{ url: '/pet' }] as const
43
+ ```
44
+
45
+ ## Extend the default key
46
+
47
+ When you need your own entry, such as an API version, set [`queryKey`](https://kubb.dev/extensions/kubb-labs/plugin-swr/options#querykey) and spread `queryKeyTransformer`. Do not read single entries of its result: they can change between releases.
48
+
49
+ > [!WARNING]
50
+ > Returned strings are copied into the generated code as written. Wrap a string literal in `JSON.stringify(...)`.
51
+
52
+ ::code-group
53
+
54
+ ```typescript [kubb.config.ts]
55
+ import { defineConfig } from 'kubb/config'
56
+ import { pluginTs } from '@kubb/plugin-ts'
57
+ import { pluginFetch } from '@kubb/plugin-fetch'
58
+ import { pluginSwr, queryKeyTransformer } from '@kubb/plugin-swr'
59
+
60
+ export default defineConfig({
61
+ input: './petStore.yaml',
62
+ output: { path: './src/gen' },
63
+ plugins: [
64
+ pluginTs(),
65
+ pluginFetch(),
66
+ pluginSwr({
67
+ queryKey: (props) => [JSON.stringify(props.node.operationId), ...queryKeyTransformer(props)],
68
+ }),
69
+ ],
70
+ })
71
+ ```
72
+
73
+ ```typescript [Generated]
74
+ export const findPetsByTagsQueryKey = ({ query }: Omit<FindPetsByTagsOptions, 'headers'> = {}) =>
75
+ ["findPetsByTags", { url: '/pet/findByTags' }, ...(query ? [query] : [])] as const
76
+ ```
77
+
78
+ ::
79
+
80
+ [`mutationKey`](https://kubb.dev/extensions/kubb-labs/plugin-swr/options#mutationkey) works the same way with `mutationKeyTransformer`.
81
+
82
+ ## Revalidate every call of an operation
83
+
84
+ SWR's `mutate` matches the whole key, not a prefix. To revalidate every cached call of an operation, give the keys your own first entry, as above, and pass a filter function:
85
+
86
+ ```typescript
87
+ import { mutate } from 'swr'
88
+
89
+ await mutate((key) => Array.isArray(key) && key[0] === 'findPetsByTags')
90
+ ```
91
+
92
+ Next, [skip requests until ready](https://kubb.dev/extensions/kubb-labs/plugin-swr/guides/calling-operations#skip-requests-until-ready) with `shouldFetch`.
package/docs/options.md CHANGED
@@ -1,30 +1,33 @@
1
1
  # Options
2
2
 
3
- Pass these options to `pluginSwr()`, all of them optional. Shared options link to [Shared plugin options](https://kubb.dev/docs/5.x/reference/plugin-options) for details.
3
+ Pass these options to `pluginSwr()`. Shared options link to [Shared plugin options](https://kubb.dev/docs/5.x/reference/plugin-options).
4
4
 
5
5
  ## Options overview
6
6
 
7
- | Option | Purpose | Default |
8
- | ------------------------------------------------------------------------- | ---------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
9
- | [`output`](https://kubb.dev/docs/5.x/reference/plugin-options#output) | Where files are written: `path`, `mode`, `barrel`, `banner`, `footer`. | `{ path: 'hooks', barrel: { type: 'named' } }` |
10
- | [`group`](https://kubb.dev/docs/5.x/reference/plugin-options#group) | Split output by tag or path: `type`, `name`. | None |
11
- | [`client`](#client) | Which registered client plugin the hooks call. | Auto-detected |
12
- | [`returnType`](#returntype) | Shape of the value the hooks resolve to. | `'data'` |
13
- | [`query`](#query) | Configure the `useSWR` hooks, or turn them off. | `{ methods: ['GET', 'QUERY'], importPath: 'swr' }` |
14
- | [`queryKey`](#querykey) | Build the SWR key for each query hook. | Exported `queryKeyTransformer` |
15
- | [`mutation`](#mutation) | Configure the `useSWRMutation` hooks, or turn them off. | `{ methods: ['POST', 'PUT', 'PATCH', 'DELETE'], importPath: 'swr/mutation' }` |
16
- | [`mutationKey`](#mutationkey) | Build the SWR key for each mutation hook. | Exported `mutationKeyTransformer` |
17
- | [`include`](https://kubb.dev/docs/5.x/reference/plugin-options#include) | Keep only operations that match. | None |
18
- | [`exclude`](https://kubb.dev/docs/5.x/reference/plugin-options#exclude) | Skip operations that match. | `[]` |
19
- | [`override`](https://kubb.dev/docs/5.x/reference/plugin-options#override) | Apply different options per pattern. | `[]` |
20
- | [`resolver`](#resolver) | Customize generated names and file paths. | `resolverSwr` |
21
- | [`macros`](https://kubb.dev/docs/5.x/reference/plugin-options#macros) | Rewrite AST nodes before printing. | `[]` |
7
+ | Option | Purpose | Default |
8
+ | ------------------------------------------------------------------------- | ------------------------------------------------------------ | ----------------------------------------------------------------------------- |
9
+ | [`client`](#client) | Which registered client plugin the hooks call. | Auto-detected |
10
+ | [`returnType`](#returntype) | What the hooks resolve to. | `'data'` |
11
+ | [`query`](#query) | Which methods become `useSWR` hooks, and the import. | `{ methods: ['GET', 'QUERY'], importPath: 'swr' }` |
12
+ | [`queryKey`](#querykey) | Build the SWR key of each query. | `queryKeyTransformer` |
13
+ | [`mutation`](#mutation) | Which methods become `useSWRMutation` hooks, and the import. | `{ methods: ['POST', 'PUT', 'PATCH', 'DELETE'], importPath: 'swr/mutation' }` |
14
+ | [`mutationKey`](#mutationkey) | Build the SWR key of each mutation. | `mutationKeyTransformer` |
15
+ | [`output`](https://kubb.dev/docs/5.x/reference/plugin-options#output) | Where files are written. | `{ path: 'hooks', barrel: { type: 'named' } }` |
16
+ | [`group`](https://kubb.dev/docs/5.x/reference/plugin-options#group) | Split output by tag or path. | None |
17
+ | [`include`](https://kubb.dev/docs/5.x/reference/plugin-options#include) | Keep only operations that match. | None |
18
+ | [`exclude`](https://kubb.dev/docs/5.x/reference/plugin-options#exclude) | Skip operations that match. | `[]` |
19
+ | [`override`](https://kubb.dev/docs/5.x/reference/plugin-options#override) | Apply different options per pattern. | `[]` |
20
+ | [`resolver`](#resolver) | Customize generated names and file paths. | `resolverSwr` |
21
+ | [`macros`](https://kubb.dev/docs/5.x/reference/plugin-options#macros) | Rewrite AST nodes before printing. | `[]` |
22
+
23
+ > [!NOTE]
24
+ > The plugin always generates hooks, so it has no `hooks` option. It does not generate `useSWRInfinite` or suspense hooks.
22
25
 
23
26
  ## Option details
24
27
 
25
28
  ### client
26
29
 
27
- Selects which registered client plugin the hooks call. A single registered client is auto-detected. Set `client` when several are registered.
30
+ The registered client plugin whose functions the hooks call. A lone client plugin is detected, so set `client` only when several are registered. Generation fails when none is registered.
28
31
 
29
32
  | | |
30
33
  | -------- | -------------------------------- |
@@ -34,55 +37,52 @@ Selects which registered client plugin the hooks call. A single registered clien
34
37
  ::field-group
35
38
 
36
39
  :::field{name="'fetch'"}
37
- Calls the operations generated by [`@kubb/plugin-fetch`](https://kubb.dev/extensions/kubb-labs/plugin-fetch).
40
+ Calls [`@kubb/plugin-fetch`](https://kubb.dev/extensions/kubb-labs/plugin-fetch) functions.
38
41
  :::
39
42
 
40
43
  :::field{name="'axios'"}
41
- Calls the operations generated by [`@kubb/plugin-axios`](https://kubb.dev/extensions/kubb-labs/plugin-axios).
44
+ Calls [`@kubb/plugin-axios`](https://kubb.dev/extensions/kubb-labs/plugin-axios) functions.
42
45
  :::
43
46
 
44
47
  :::field{name="'client'"}
45
- Calls the operations generated by [`@kubb/plugin-client`](https://kubb.dev/extensions/kubb-labs/plugin-client). The client module must also export the `RequestConfig` and `ResponseErrorConfig` types.
48
+ Calls [`@kubb/plugin-client`](https://kubb.dev/extensions/kubb-labs/plugin-client) functions. Your client module must also export the `RequestConfig` and `ResponseErrorConfig` types.
46
49
  :::
47
50
 
48
51
  ::
49
52
 
50
53
  ### returnType
51
54
 
52
- Shape of the value the generated hooks resolve to.
55
+ What the hooks resolve to.
53
56
 
54
57
  | | |
55
58
  | -------- | ------------------ |
56
- | Type | `'full' \| 'data'` |
59
+ | Type | `'data' \| 'full'` |
57
60
  | Required | `false` |
58
61
  | Default | `'data'` |
59
62
 
60
63
  ::field-group
61
64
 
62
- :::field{name="'full'"}
63
- Returns the client's whole `RequestResult` (`{ status, data, error, contentType, headers, request, response }`), so a hook can read the status and the response headers next to `data`. Needs a client plugin whose own `returnType` is `'full'` or `'plain'`. With a client `returnType: 'data'`, generation stops with an error.
65
+ :::field{name="'data'"}
66
+ Default. Resolves to the success body.
64
67
  :::
65
68
 
66
- :::field{name="'data'"}
67
- Returns the success body.
69
+ :::field{name="'full'"}
70
+ Resolves to the client's whole `RequestResult`, so a hook can read the status and response headers. Needs a client plugin with `returnType` `'full'` or `'plain'`, or generation stops with an error.
68
71
  :::
69
72
 
70
73
  ::
71
74
 
72
- ```ts
75
+ ```typescript
73
76
  pluginSwr({ returnType: 'full' })
74
77
 
78
+ // with integerType: 'number' on the adapter
75
79
  const { data: result } = useGetPetById({ path: { petId: 1 } })
76
-
77
80
  const etag = result?.response.headers.get('ETag')
78
- const pet = result?.data
79
81
  ```
80
82
 
81
- 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`.
82
-
83
83
  ### query
84
84
 
85
- Configures the generated `useSWR` hooks. Pass an object to change the HTTP methods or import path, or `false` to skip query hook generation.
85
+ Which operations become `useSWR` hooks and where `useSWR` is imported from. `false` skips query output.
86
86
 
87
87
  | | |
88
88
  | -------- | -------------------------------------------------- |
@@ -92,7 +92,7 @@ Configures the generated `useSWR` hooks. Pass an object to change the HTTP metho
92
92
 
93
93
  #### query.methods
94
94
 
95
- HTTP methods treated as queries. An operation whose method is in this list generates a `useSWR` hook instead of a mutation.
95
+ HTTP methods treated as queries. A method in neither `query.methods` nor `mutation.methods` gets no hook, so keep `'QUERY'` when you replace the list.
96
96
 
97
97
  | | |
98
98
  | -------- | ------------------ |
@@ -100,11 +100,9 @@ HTTP methods treated as queries. An operation whose method is in this list gener
100
100
  | Required | `false` |
101
101
  | Default | `['GET', 'QUERY']` |
102
102
 
103
- Operations whose method is in neither `query.methods` nor `mutation.methods` get no hook. Keep `'QUERY'` here when overriding the list, or QUERY operations are skipped.
104
-
105
103
  #### query.importPath
106
104
 
107
- Module that `useSWR` is imported from, emitted as `import useSWR from '${importPath}'`. Relative and absolute paths are used as written, with relative paths resolved against the generated file.
105
+ Module of the default `useSWR` import, written as `import useSWR from '<importPath>'`. A relative path resolves from the generated file.
108
106
 
109
107
  | | |
110
108
  | -------- | -------- |
@@ -114,29 +112,28 @@ Module that `useSWR` is imported from, emitted as `import useSWR from '${importP
114
112
 
115
113
  ### queryKey
116
114
 
117
- Builds the SWR key for each query hook. The callback receives the operation `node`, the active `casing` and `variant: 'query'` and returns the key array. Strings are copied into the generated code as written, so wrap a string literal in `JSON.stringify(...)`.
115
+ Builds each query's SWR key from the operation `node` and `variant: 'query'`. The default key is `[{ url, params }, query, body]`, with only the parts the operation has.
118
116
 
119
117
  | | |
120
118
  | -------- | ------------------------------------------------------ |
121
119
  | Type | `(props: { node, casing, variant }) => Array<unknown>` |
122
120
  | Required | `false` |
123
- | Default | Exported `queryKeyTransformer` |
121
+ | Default | `queryKeyTransformer` |
124
122
 
125
- ```typescript
126
- queryKey: ({ node, variant }) => [JSON.stringify({ variant, operationId: node.operationId })]
127
- ```
123
+ > [!WARNING]
124
+ > Returned strings are copied into the generated code as written. Wrap a string literal in `JSON.stringify(...)`.
128
125
 
129
- To extend the default key instead of replacing it, import `queryKeyTransformer` and spread its result. The default segments can change between releases, so spread them instead of reading single entries.
126
+ To extend the default, spread it. Single entries can change between releases. See [SWR keys](https://kubb.dev/extensions/kubb-labs/plugin-swr/guides/query-keys).
130
127
 
131
128
  ```typescript
132
129
  import { queryKeyTransformer } from '@kubb/plugin-swr'
133
130
 
134
- queryKey: (props) => [JSON.stringify(props.node.operationId), ...queryKeyTransformer(props)]
131
+ queryKey: (props) => [JSON.stringify('v2'), ...queryKeyTransformer(props)]
135
132
  ```
136
133
 
137
134
  ### mutation
138
135
 
139
- Configures the generated `useSWRMutation` hooks. Pass an object to change the HTTP methods or import path, or `false` to skip mutation hook generation.
136
+ Which operations become `useSWRMutation` hooks and where `useSWRMutation` is imported from. `false` skips mutation output.
140
137
 
141
138
  | | |
142
139
  | -------- | ----------------------------------------------------------------------------- |
@@ -146,7 +143,7 @@ Configures the generated `useSWRMutation` hooks. Pass an object to change the HT
146
143
 
147
144
  #### mutation.methods
148
145
 
149
- HTTP methods treated as mutations. An operation whose method is in this list generates a `useSWRMutation` hook instead of a query.
146
+ HTTP methods treated as mutations. A method also in `query.methods` stays a query.
150
147
 
151
148
  | | |
152
149
  | -------- | ------------------------------------ |
@@ -156,7 +153,7 @@ HTTP methods treated as mutations. An operation whose method is in this list gen
156
153
 
157
154
  #### mutation.importPath
158
155
 
159
- Module that `useSWRMutation` is imported from, emitted as `import useSWRMutation from '${importPath}'`. Relative and absolute paths are used as written, with relative paths resolved against the generated file.
156
+ Module of the default `useSWRMutation` import, written as `import useSWRMutation from '<importPath>'`. A relative path resolves from the generated file.
160
157
 
161
158
  | | |
162
159
  | -------- | ---------------- |
@@ -166,25 +163,23 @@ Module that `useSWRMutation` is imported from, emitted as `import useSWRMutation
166
163
 
167
164
  ### mutationKey
168
165
 
169
- Builds the SWR key for each mutation hook. Like `queryKey`, the callback receives the operation `node`, the active `casing` and `variant: 'mutation'` and returns the key array. Strings are copied into the generated code as written, so wrap a string literal in `JSON.stringify(...)`.
166
+ Builds each mutation's SWR key, for matching keys in SWR's global `mutate`. It takes the same props as [`queryKey`](#querykey) with `variant: 'mutation'`, and copies strings the same way. The default key is `[{ url }]`.
170
167
 
171
168
  | | |
172
169
  | -------- | ------------------------------------------------------ |
173
170
  | Type | `(props: { node, casing, variant }) => Array<unknown>` |
174
171
  | Required | `false` |
175
- | Default | Exported `mutationKeyTransformer` |
176
-
177
- Extend the default the same way with `mutationKeyTransformer`:
172
+ | Default | `mutationKeyTransformer` |
178
173
 
179
174
  ```typescript
180
175
  import { mutationKeyTransformer } from '@kubb/plugin-swr'
181
176
 
182
- mutationKey: (props) => [JSON.stringify(props.node.operationId), ...mutationKeyTransformer(props)]
177
+ mutationKey: (props) => [JSON.stringify('v2'), ...mutationKeyTransformer(props)]
183
178
  ```
184
179
 
185
180
  ### resolver
186
181
 
187
- Overrides generated file and symbol names. Omitted members keep `resolverSwr`. The shared members (`name`, `file`, `imports`) and the `this` context are described under [`resolver`](https://kubb.dev/docs/5.x/reference/plugin-options#resolver).
182
+ Overrides generated file and symbol names. Members you leave out keep `resolverSwr`. See [`resolver`](https://kubb.dev/docs/5.x/reference/plugin-options#resolver) for the shared `name`, `file`, and `imports` members.
188
183
 
189
184
  | | |
190
185
  | -------- | ---------------------------- |
@@ -195,23 +190,18 @@ Overrides generated file and symbol names. Omitted members keep `resolverSwr`. T
195
190
 
196
191
  ```typescript [Partial override]
197
192
  type ResolverSwrPatch = {
198
- name?(name: string): string
199
- file?: {
200
- baseName?(params: { name: string; extname: string }): string
201
- path?(params: { baseName: string; output: Output }): string
202
- }
203
- imports?(options: ResolveImportsOptions): Array<ImportNode>
193
+ // plus the shared name, file, and imports members
204
194
  query?: {
205
- name?(node: OperationNode): string // → 'useGetPetById'
206
- optionsName?(node: OperationNode): string // → 'getPetByIdQueryOptions'
207
- keyName?(node: OperationNode): string // → 'getPetByIdQueryKey'
208
- keyTypeName?(node: OperationNode): string // → 'GetPetByIdQueryKey'
195
+ name?(node: OperationNode): string // 'useGetPetById'
196
+ optionsName?(node: OperationNode): string // 'getPetByIdQueryOptions'
197
+ keyName?(node: OperationNode): string // 'getPetByIdQueryKey'
198
+ keyTypeName?(node: OperationNode): string // 'GetPetByIdQueryKey'
209
199
  }
210
200
  mutation?: {
211
- name?(node: OperationNode): string // → 'useUpdatePet'
212
- keyName?(node: OperationNode): string // → 'updatePetMutationKey'
213
- keyTypeName?(node: OperationNode): string // → 'UpdatePetMutationKey'
214
- argTypeName?(node: OperationNode): string // → 'UpdatePetMutationArg'
201
+ name?(node: OperationNode): string // 'useUpdatePet'
202
+ keyName?(node: OperationNode): string // 'updatePetMutationKey'
203
+ keyTypeName?(node: OperationNode): string // 'UpdatePetMutationKey'
204
+ argTypeName?(node: OperationNode): string // 'UpdatePetMutationArg'
215
205
  }
216
206
  }
217
207
  ```
package/docs/overview.md CHANGED
@@ -1,27 +1,27 @@
1
1
  # SWR
2
2
 
3
- The SWR plugin generates a `useSWR` hook for each query and a `useSWRMutation` hook for each mutation.
3
+ The SWR plugin generates a `useSWR` hook for each query and a `useSWRMutation` hook for each mutation in your OpenAPI spec, with their cache keys.
4
4
 
5
- The plugin ships no HTTP client. Each hook calls a function generated by a client plugin.
5
+ - The plugin ships no HTTP client. Each hook calls a function from your client plugin.
6
+ - The plugin does not generate `useSWRInfinite` or suspense hooks.
6
7
 
7
8
  ## Setup
8
9
 
9
- - Add `@kubb/plugin-ts`, or `pluginZod({ inferred: 'codec' })` for codec types, and a client plugin: `@kubb/plugin-fetch`, `@kubb/plugin-axios`, or `@kubb/plugin-client`. Leave `sdk` unset on the client plugin.
10
- - Install `swr` 2.2 or a later v2 release in the app that uses the generated code.
11
- - Configure validation on the client plugin, not here.
10
+ - Add `@kubb/plugin-ts`, or `pluginZod({ inferred: 'codec' })` with `zod` v4 in the app.
11
+ - Add one client plugin: `@kubb/plugin-fetch`, `@kubb/plugin-axios`, or `@kubb/plugin-client`. Leave `sdk` unset on it.
12
+ - Install `swr` 2.2 or a later v2 release in the app.
13
+ - Set the base URL, auth, and validation on the client plugin. With `@kubb/plugin-client`, your client module owns them.
12
14
 
13
15
  ## Options worth knowing
14
16
 
15
- - `client` picks `fetch`, `axios`, or `client` when more than one client plugin is registered. A single client plugin is detected automatically.
16
- - `query` and `mutation` set which HTTP methods become queries (`GET`, `QUERY`) and mutations (`POST`, `PUT`, `PATCH`, `DELETE`). They also set where SWR is imported from (`swr` and `swr/mutation`). Set either to `false` to skip those hooks.
17
-
18
- The plugin does not generate `useSWRInfinite` hooks.
19
-
20
- See [Options](https://kubb.dev/extensions/kubb-labs/plugin-swr/options) for every option and its default.
17
+ | Option | What it does |
18
+ | ------------------- | ------------------------------------------------------------------------------------- |
19
+ | `client` | Picks `'fetch'`, `'axios'`, or `'client'` when several client plugins are registered. |
20
+ | `query`, `mutation` | Which HTTP methods become queries and mutations. `false` skips them. |
21
21
 
22
22
  ## Example
23
23
 
24
- The config below generates `useSWR` and `useSWRMutation` hooks that call the Fetch client.
24
+ This config generates hooks that call the Fetch client.
25
25
 
26
26
  ```typescript [kubb.config.ts]
27
27
  import { defineConfig } from 'kubb/config'
@@ -41,3 +41,5 @@ export default defineConfig({
41
41
  ],
42
42
  })
43
43
  ```
44
+
45
+ See [Options](https://kubb.dev/extensions/kubb-labs/plugin-swr/options) for every option. Next, [call operations](https://kubb.dev/extensions/kubb-labs/plugin-swr/guides/calling-operations).
@@ -19,7 +19,7 @@
19
19
  ],
20
20
  "optionalDependencies": ["plugin-ts", "plugin-zod"],
21
21
  "compatibility": {
22
- "kubb": ">=5.18.4",
22
+ "kubb": ">=5.19.0",
23
23
  "node": ">=22.22"
24
24
  },
25
25
  "role": "consumer",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubb/plugin-swr",
3
- "version": "5.9.2",
3
+ "version": "5.9.4",
4
4
  "description": "Generate type-safe SWR hooks with Kubb. Covers useSWR and useSWRMutation with full TypeScript support.",
5
5
  "keywords": [
6
6
  "code-generation",
@@ -79,16 +79,16 @@
79
79
  "registry": "https://registry.npmjs.org/"
80
80
  },
81
81
  "dependencies": {
82
- "@kubb/kit": "^5.19.0",
83
- "@kubb/plugin-ts": "^5.5.2",
84
- "@kubb/renderer-jsx": "^5.19.0"
82
+ "@kubb/kit": "^5.20.1",
83
+ "@kubb/plugin-ts": "^5.5.4",
84
+ "@kubb/renderer-jsx": "^5.20.1"
85
85
  },
86
86
  "devDependencies": {
87
87
  "@internals/client": "0.0.0",
88
88
  "@internals/shared": "0.0.0",
89
89
  "@internals/tanstack-query": "0.0.0",
90
90
  "@internals/utils": "0.0.0",
91
- "@kubb/plugin-client": "6.0.2",
91
+ "@kubb/plugin-client": "6.0.4",
92
92
  "swr": "^2.5.1"
93
93
  },
94
94
  "peerDependencies": {