@kubb/plugin-axios 6.0.2 → 6.0.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 +2 -2
- package/dist/index.js +2 -2
- package/docs/guides/calling-operations.md +45 -80
- package/docs/guides/configure-requests.md +206 -0
- package/docs/guides/error-handling.md +73 -81
- package/docs/guides/migrate-to-v6.md +147 -202
- package/docs/guides/serialization.md +135 -91
- package/docs/guides/server-sent-events.md +136 -276
- package/docs/guides/transport.md +53 -30
- package/docs/options.md +72 -85
- package/docs/overview.md +33 -15
- package/kubb-extension.json +1 -1
- package/package.json +3 -3
- package/docs/guides/authentication.md +0 -101
- package/docs/guides/base-url.md +0 -102
- package/docs/guides/interceptors.md +0 -109
package/docs/guides/transport.md
CHANGED
|
@@ -1,28 +1,41 @@
|
|
|
1
1
|
# Use a custom transport
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Replace the network send of the generated axios client with your own axios instance or function.
|
|
4
4
|
|
|
5
|
-
The
|
|
5
|
+
The client still builds the URL, serializes parameters, resolves auth, runs interceptors, and decodes the result. `client.interceptors` handlers keep running, whatever the transport.
|
|
6
|
+
|
|
7
|
+
## Write a transport function
|
|
8
|
+
|
|
9
|
+
A transport gets the resolved request and returns a web `Response` with its body unread:
|
|
6
10
|
|
|
7
11
|
```typescript
|
|
8
|
-
type
|
|
9
|
-
|
|
10
|
-
|
|
12
|
+
type Transport = (request: ResolvedRequest) => Promise<Response | TransportResult>
|
|
13
|
+
|
|
14
|
+
type ResolvedRequest = {
|
|
15
|
+
url: string // built, with the query
|
|
16
|
+
method: string
|
|
17
|
+
headers: Record<string, string> // auth headers included
|
|
18
|
+
body?: RequestBody // already encoded
|
|
19
|
+
signal?: AbortSignal
|
|
20
|
+
credentials?: RequestCredentials
|
|
21
|
+
options?: NativeOptions // AxiosRequestConfig
|
|
22
|
+
stream?: boolean // the call streams the response, so do not buffer the body
|
|
11
23
|
}
|
|
24
|
+
|
|
25
|
+
type TransportResult = { webResponse: Response; request: AxiosRequestConfig; response: AxiosResponse }
|
|
12
26
|
```
|
|
13
27
|
|
|
14
|
-
|
|
28
|
+
Return a `TransportResult` to set the native `request` and `response` that results and errors carry. See [Results from a plain `Response`](#results-from-a-plain-response).
|
|
29
|
+
|
|
30
|
+
## Send through your own axios instance
|
|
15
31
|
|
|
16
|
-
|
|
32
|
+
`createAxiosTransport(instance)` turns any axios instance into a transport, with its defaults, adapter, and interceptors:
|
|
17
33
|
|
|
18
34
|
```typescript
|
|
19
35
|
import axios from 'axios'
|
|
20
36
|
import { client, createAxiosTransport } from './gen/.kubb/client'
|
|
21
37
|
|
|
22
|
-
const instance = axios.create({
|
|
23
|
-
timeout: 10_000,
|
|
24
|
-
headers: { 'X-Client': 'kubb' },
|
|
25
|
-
})
|
|
38
|
+
const instance = axios.create({ timeout: 10_000, headers: { 'X-Client': 'kubb' } })
|
|
26
39
|
|
|
27
40
|
instance.interceptors.response.use((response) => {
|
|
28
41
|
console.info(`${response.config.method?.toUpperCase()} ${response.config.url} -> ${response.status}`)
|
|
@@ -32,39 +45,49 @@ instance.interceptors.response.use((response) => {
|
|
|
32
45
|
client.setConfig({ transport: createAxiosTransport(instance) })
|
|
33
46
|
```
|
|
34
47
|
|
|
35
|
-
Every generated function now sends through your instance, so its timeout, headers, and axios interceptors apply to each call. Handlers registered through `client.interceptors` keep running, whatever the transport.
|
|
36
|
-
|
|
37
48
|
> [!NOTE]
|
|
38
|
-
> Kubb sets `url`, `method`, `headers`, `data`, `transformRequest`, `transformResponse`, `responseType`, and `validateStatus
|
|
49
|
+
> Kubb sets `url`, `method`, `headers`, `data`, `transformRequest`, `transformResponse`, `responseType`, and `validateStatus`, so leave those alone. For one call, pass `options`, such as `{ timeout }`, instead of a new instance.
|
|
39
50
|
|
|
40
|
-
##
|
|
51
|
+
## Wrap the default transport
|
|
41
52
|
|
|
42
|
-
|
|
53
|
+
`defaultTransport` sends through the instance `getAxiosInstance()` returns. Configure that instance, or wrap the transport to add tracing or timing:
|
|
43
54
|
|
|
44
55
|
```typescript
|
|
45
|
-
import { getAxiosInstance } from './gen/.kubb/client'
|
|
56
|
+
import { client, defaultTransport, getAxiosInstance } from './gen/.kubb/client'
|
|
46
57
|
|
|
47
58
|
getAxiosInstance().defaults.timeout = 10_000
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
59
|
+
|
|
60
|
+
client.setConfig({
|
|
61
|
+
transport: (request) => withSpan(request, () => defaultTransport(request)),
|
|
51
62
|
})
|
|
52
63
|
```
|
|
53
64
|
|
|
54
|
-
|
|
65
|
+
## Mock the network in tests
|
|
66
|
+
|
|
67
|
+
Return a fixed `Response` from a separate client, and pass it to the call or to a query plugin:
|
|
68
|
+
|
|
69
|
+
```typescript
|
|
70
|
+
import { createClient } from './gen/.kubb/client'
|
|
71
|
+
import { getPetById } from './gen/clients/getPetById'
|
|
72
|
+
|
|
73
|
+
const testClient = createClient({ transport: async () => Response.json({ id: 1, name: 'Fluffy' }) })
|
|
74
|
+
|
|
75
|
+
const { data } = await getPetById({ path: { petId: 1 }, client: testClient })
|
|
76
|
+
// ^ { id: 1, name: 'Fluffy' }
|
|
77
|
+
```
|
|
55
78
|
|
|
56
79
|
## Where to set it
|
|
57
80
|
|
|
58
|
-
|
|
81
|
+
| Scope | How |
|
|
82
|
+
| ----------------- | --------------------------------- |
|
|
83
|
+
| Every call | `client.setConfig({ transport })` |
|
|
84
|
+
| A separate client | `createClient({ transport })` |
|
|
85
|
+
| One call | `transport` on the call |
|
|
59
86
|
|
|
60
|
-
|
|
87
|
+
A client from `createClient()` copies the shared `transport` at creation, so a later `client.setConfig({ transport })` does not reach it. Without a `transport`, it sends through `getAxiosInstance()`.
|
|
61
88
|
|
|
62
|
-
|
|
89
|
+
## Less common cases
|
|
63
90
|
|
|
64
|
-
|
|
65
|
-
import { client, defaultTransport } from './gen/.kubb/client'
|
|
91
|
+
### Results from a plain `Response`
|
|
66
92
|
|
|
67
|
-
|
|
68
|
-
transport: (request) => withSpan(request, () => defaultTransport(request)),
|
|
69
|
-
})
|
|
70
|
-
```
|
|
93
|
+
When a transport returns a plain `Response`, results and errors carry it as `response`. Their `request` is a `Request` built from the resolved request without its body, or the resolved request itself when `Request` cannot parse the URL, such as a relative URL in Node.js. Return a `TransportResult` to set both, as [Write a transport function](#write-a-transport-function) shows.
|
package/docs/options.md
CHANGED
|
@@ -4,35 +4,46 @@ Pass these options to `pluginAxios()`. Shared options link to [Shared plugin opt
|
|
|
4
4
|
|
|
5
5
|
## Options overview
|
|
6
6
|
|
|
7
|
-
| Option | Purpose
|
|
8
|
-
| ------------------------------------------------------------------------- |
|
|
9
|
-
| [`output`](https://kubb.dev/docs/5.x/reference/plugin-options#output) | Where files are written
|
|
10
|
-
| [`group`](https://kubb.dev/docs/5.x/reference/plugin-options#group) | Split output by tag or path
|
|
11
|
-
| [`baseURL`](#baseurl) | Base URL
|
|
12
|
-
| [`throwOnErrorDefault`](#throwonerrordefault) |
|
|
13
|
-
| [`validator`](#validator) | Validate
|
|
14
|
-
| [`
|
|
15
|
-
| [`
|
|
16
|
-
| [`
|
|
17
|
-
| [`
|
|
18
|
-
| [`
|
|
19
|
-
| [`
|
|
20
|
-
| [`
|
|
7
|
+
| Option | Purpose | Default |
|
|
8
|
+
| ------------------------------------------------------------------------- | ----------------------------------------------------------- | ------------------------------------------------ |
|
|
9
|
+
| [`output`](https://kubb.dev/docs/5.x/reference/plugin-options#output) | Where files are written. | `{ path: 'clients', barrel: { type: 'named' } }` |
|
|
10
|
+
| [`group`](https://kubb.dev/docs/5.x/reference/plugin-options#group) | Split output by tag or path. | None |
|
|
11
|
+
| [`baseURL`](#baseurl) | Base URL the client starts with. | None |
|
|
12
|
+
| [`throwOnErrorDefault`](#throwonerrordefault) | Throw on a non-2xx response unless a call says otherwise. | `true` |
|
|
13
|
+
| [`validator`](#validator) | Validate requests and responses with Zod. | `false` |
|
|
14
|
+
| [`returnType`](#returntype) | What a call resolves to. | `'full'` |
|
|
15
|
+
| [`sdk`](#sdk) | Generate classes instead of standalone functions. | None |
|
|
16
|
+
| [`sdk.mode`](#sdk) | One class per tag, or one class with every operation. | `'tag'` |
|
|
17
|
+
| [`sdk.name`](#sdk) | Name and file of the root or flat class. | None, or `'sdk'` with `mode: 'flat'` |
|
|
18
|
+
| [`include`](https://kubb.dev/docs/5.x/reference/plugin-options#include) | Keep only operations that match. | None |
|
|
19
|
+
| [`exclude`](https://kubb.dev/docs/5.x/reference/plugin-options#exclude) | Skip operations that match. | `[]` |
|
|
20
|
+
| [`override`](https://kubb.dev/docs/5.x/reference/plugin-options#override) | Options per pattern, except `throwOnErrorDefault`. | `[]` |
|
|
21
|
+
| [`resolver`](https://kubb.dev/docs/5.x/reference/plugin-options#resolver) | Generated names and paths, plus the [SDK names](#resolver). | `resolverClient` |
|
|
22
|
+
| [`macros`](https://kubb.dev/docs/5.x/reference/plugin-options#macros) | Rewrite AST nodes before printing. | `[]`, run after the built-in client macros |
|
|
21
23
|
|
|
22
24
|
## Option details
|
|
23
25
|
|
|
24
26
|
### baseURL
|
|
25
27
|
|
|
26
|
-
|
|
28
|
+
The base URL the client starts with. `client.setConfig({ baseURL })` replaces it at runtime.
|
|
27
29
|
|
|
28
30
|
| | |
|
|
29
31
|
| -------- | -------- |
|
|
30
32
|
| Type | `string` |
|
|
31
33
|
| Required | `false` |
|
|
32
34
|
|
|
35
|
+
A `${...}` interpolation becomes a template literal, so it reads the environment at runtime:
|
|
36
|
+
|
|
37
|
+
```typescript
|
|
38
|
+
pluginAxios({ baseURL: '${process.env.API_URL}' })
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
> [!NOTE]
|
|
42
|
+
> The spec's top-level `servers` URL is never used. See [Set the base URL](https://kubb.dev/extensions/kubb-labs/plugin-axios/guides/configure-requests#set-the-base-url).
|
|
43
|
+
|
|
33
44
|
### throwOnErrorDefault
|
|
34
45
|
|
|
35
|
-
|
|
46
|
+
The `throwOnError` a generated function or SDK method uses when the call leaves it out. Neither `override` nor `client.setConfig({ throwOnError })` changes it. Query hooks always pass `throwOnError: true`.
|
|
36
47
|
|
|
37
48
|
| | |
|
|
38
49
|
| -------- | --------- |
|
|
@@ -43,14 +54,12 @@ Set `throwOnErrorDefault: false` to return documented error responses as values
|
|
|
43
54
|
```typescript
|
|
44
55
|
// with pluginAxios({ throwOnErrorDefault: false })
|
|
45
56
|
const result = await getPetById({ path: { petId: 1 } })
|
|
46
|
-
if (result.
|
|
57
|
+
if (result.error !== undefined) console.error(result.status, result.error)
|
|
47
58
|
```
|
|
48
59
|
|
|
49
|
-
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`.
|
|
50
|
-
|
|
51
60
|
### validator
|
|
52
61
|
|
|
53
|
-
|
|
62
|
+
Checks requests and responses against the schemas of `@kubb/plugin-zod`, so add `pluginZod()` too. A value that fails its schema throws a `ParseError`.
|
|
54
63
|
|
|
55
64
|
| | |
|
|
56
65
|
| -------- | ------------------------------------------------------------------------- |
|
|
@@ -61,15 +70,15 @@ Validates request bodies, the path, query, header, and cookie params, and respon
|
|
|
61
70
|
::field-group
|
|
62
71
|
|
|
63
72
|
:::field{name="false"}
|
|
64
|
-
Default value.
|
|
73
|
+
Default value. No validation. The response is cast to the generated type.
|
|
65
74
|
:::
|
|
66
75
|
|
|
67
76
|
:::field{name="'zod'"}
|
|
68
|
-
Validates the success
|
|
77
|
+
Validates the success body, and an error body against the schema of its status.
|
|
69
78
|
:::
|
|
70
79
|
|
|
71
80
|
:::field{name="{ request?: 'zod', params?: 'zod', response?: 'zod' }"}
|
|
72
|
-
|
|
81
|
+
Opts in per part. `request` checks the body and `params` the path, query, header, and cookie params before the send. `response` works as `'zod'`.
|
|
73
82
|
:::
|
|
74
83
|
|
|
75
84
|
::
|
|
@@ -83,109 +92,87 @@ import { pluginAxios } from '@kubb/plugin-axios'
|
|
|
83
92
|
export default defineConfig({
|
|
84
93
|
input: './petStore.yaml',
|
|
85
94
|
output: { path: './src/gen' },
|
|
86
|
-
plugins: [
|
|
87
|
-
pluginTs(),
|
|
88
|
-
pluginZod(),
|
|
89
|
-
pluginAxios({ validator: { request: 'zod', params: 'zod', response: 'zod' } }),
|
|
90
|
-
],
|
|
95
|
+
plugins: [pluginTs(), pluginZod(), pluginAxios({ validator: { request: 'zod', params: 'zod', response: 'zod' } })],
|
|
91
96
|
})
|
|
92
97
|
```
|
|
93
98
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
Only the params your OpenAPI spec declares are sent. Path and query keys the spec does not declare are stripped, so a key such as an undocumented filter or a cache-buster never reaches the URL. Declare it in the spec, or leave `params` off. Headers are the exception. Client-level `headers`, such as `Authorization` or tracing headers, are merged with the call's headers before validation. Headers the spec does not declare pass through unchanged, and declared header params match in any casing.
|
|
99
|
+
See [Turn validation off at runtime](https://kubb.dev/extensions/kubb-labs/plugin-axios/guides/error-handling#turn-validation-off-at-runtime) and [Parameter validation](https://kubb.dev/extensions/kubb-labs/plugin-axios/guides/serialization#parameter-validation).
|
|
97
100
|
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
### sdk
|
|
101
|
+
### returnType
|
|
101
102
|
|
|
102
|
-
|
|
103
|
+
What a generated function or SDK method resolves to. The query plugins and `@kubb/plugin-mcp` read it too.
|
|
103
104
|
|
|
104
|
-
| |
|
|
105
|
-
| -------- |
|
|
106
|
-
| Type | `
|
|
107
|
-
| Required | `false`
|
|
105
|
+
| | |
|
|
106
|
+
| -------- | ------------------ |
|
|
107
|
+
| Type | `'full' \| 'data'` |
|
|
108
|
+
| Required | `false` |
|
|
109
|
+
| Default | `'full'` |
|
|
108
110
|
|
|
109
111
|
::field-group
|
|
110
112
|
|
|
111
|
-
:::field{name="'
|
|
112
|
-
Default value
|
|
113
|
+
:::field{name="'full'"}
|
|
114
|
+
Default value. The full result: `{ status, data, error, contentType, headers, request, response }`.
|
|
113
115
|
:::
|
|
114
116
|
|
|
115
|
-
:::field{name="'
|
|
116
|
-
|
|
117
|
+
:::field{name="'data'"}
|
|
118
|
+
The success body. With `throwOnError: false`, the full result, so the caller can tell an error from a success.
|
|
117
119
|
:::
|
|
118
120
|
|
|
119
121
|
::
|
|
120
122
|
|
|
121
|
-
`mode: 'tag'` needs one file per tag, so it throws [`KUBB_INVALID_PLUGIN_OPTIONS`](https://kubb.dev/docs/5.x/reference/diagnostics#kubb-invalid-plugin-options) with single-file output. Use `mode: 'flat'` for a single file.
|
|
122
|
-
|
|
123
|
-
Methods take the same grouped options and return the same result as the standalone functions. See [Call operations](https://kubb.dev/extensions/kubb-labs/plugin-axios/guides/calling-operations).
|
|
124
|
-
|
|
125
123
|
```typescript
|
|
126
|
-
|
|
127
|
-
const { data } = await pet.getPetById({ path: { petId: 1 } })
|
|
128
|
-
```
|
|
129
|
-
|
|
130
|
-
Each SDK class exposes its client as the read-only `client` field. Interceptors on the root class's `client` apply to every tag:
|
|
124
|
+
pluginAxios({ returnType: 'data' })
|
|
131
125
|
|
|
132
|
-
|
|
133
|
-
const api = new PetStore({ baseURL: 'https://petstore.swagger.io/v2' })
|
|
134
|
-
api.client.interceptors.request.use((request) => request)
|
|
135
|
-
await api.pet.getPetById({ path: { petId: 1 } })
|
|
126
|
+
const pet = await getPetById({ path: { petId: 1 } }) // Pet, not { status, data, ... }
|
|
136
127
|
```
|
|
137
128
|
|
|
138
|
-
|
|
129
|
+
See [Read headers with `returnType: 'data'`](https://kubb.dev/extensions/kubb-labs/plugin-axios/guides/error-handling#read-headers-with-returntype-data).
|
|
139
130
|
|
|
140
|
-
###
|
|
131
|
+
### sdk
|
|
141
132
|
|
|
142
|
-
|
|
133
|
+
Generates classes instead of standalone functions. Each instance builds its own client from its config, so two environments are two instances.
|
|
143
134
|
|
|
144
|
-
| |
|
|
145
|
-
| -------- |
|
|
146
|
-
| Type | `'
|
|
147
|
-
| Required | `false`
|
|
148
|
-
| Default | `'full'` |
|
|
135
|
+
| | |
|
|
136
|
+
| -------- | ------------------------------------------- |
|
|
137
|
+
| Type | `{ mode?: 'tag' \| 'flat'; name?: string }` |
|
|
138
|
+
| Required | `false` |
|
|
149
139
|
|
|
150
140
|
::field-group
|
|
151
141
|
|
|
152
|
-
:::field{name="'
|
|
153
|
-
Default value.
|
|
142
|
+
:::field{name="mode: 'tag'"}
|
|
143
|
+
Default value. One class per tag, such as `PetClient`. With `name`, a root class also shares one client with every tag: `new PetStore(config).pet.getPetById(...)`. Throws [`KUBB_INVALID_PLUGIN_OPTIONS`](https://kubb.dev/docs/5.x/reference/diagnostics#kubb-invalid-plugin-options) with single-file output.
|
|
154
144
|
:::
|
|
155
145
|
|
|
156
|
-
:::field{name="'
|
|
157
|
-
|
|
146
|
+
:::field{name="mode: 'flat'"}
|
|
147
|
+
One class named by `name`, with every operation as a method. Without `name`, the class is `Sdk` in `sdk.ts`. Works with single-file output.
|
|
158
148
|
:::
|
|
159
149
|
|
|
160
150
|
::
|
|
161
151
|
|
|
152
|
+
Methods take the same options and return the same result as the standalone functions. Interceptors on the root class's `client` reach every tag:
|
|
153
|
+
|
|
162
154
|
```typescript
|
|
163
|
-
|
|
155
|
+
const api = new PetStore({ baseURL: 'https://petstore.swagger.io/v2' })
|
|
156
|
+
api.client.interceptors.request.use((request) => request)
|
|
157
|
+
await api.pet.getPetById({ path: { petId: 1 } })
|
|
164
158
|
|
|
165
|
-
const
|
|
159
|
+
const pets = new PetClient(api.client) // a tag class also accepts an existing client
|
|
166
160
|
```
|
|
167
161
|
|
|
168
|
-
|
|
162
|
+
> [!WARNING]
|
|
163
|
+
> The query plugins and `@kubb/plugin-mcp` call the standalone functions, so leave `sdk` unset for them.
|
|
169
164
|
|
|
170
165
|
### resolver
|
|
171
166
|
|
|
172
|
-
|
|
167
|
+
Adds three members to the shared [`resolver`](https://kubb.dev/docs/5.x/reference/plugin-options#resolver). Members you leave out keep `resolverClient`.
|
|
173
168
|
|
|
174
169
|
| | |
|
|
175
170
|
| -------- | ------------------------------- |
|
|
176
171
|
| Type | `ResolverPatch<ResolverClient>` |
|
|
177
172
|
| Required | `false` |
|
|
178
173
|
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
path?(params: { baseName: string; output: Output }): string
|
|
185
|
-
}
|
|
186
|
-
imports?(options: ResolveImportsOptions): Array<ImportNode>
|
|
187
|
-
className?(name: string): string
|
|
188
|
-
groupName?(name: string): string // → 'PetClient'
|
|
189
|
-
propertyName?(name: string): string
|
|
190
|
-
}
|
|
191
|
-
```
|
|
174
|
+
| Member | Names | Example |
|
|
175
|
+
| -------------------- | --------------------------------------------------------------------- | ------------------------------------ |
|
|
176
|
+
| `className(name)` | The root class, the flat class, and the class of untagged operations. | `className('petStore')` → `PetStore` |
|
|
177
|
+
| `groupName(name)` | A tag class. | `groupName('pet')` → `PetClient` |
|
|
178
|
+
| `propertyName(name)` | The field a tag class has on the root class. | `propertyName('pet')` → `pet` |
|
package/docs/overview.md
CHANGED
|
@@ -1,28 +1,30 @@
|
|
|
1
1
|
# Axios
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Generates one typed async function per OpenAPI operation that sends the request with axios and returns a result keyed by status code.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
Each function takes grouped `path`, `query`, `headers`, `cookies`, and `body` options. The query plugins and `@kubb/plugin-mcp` call these functions. The runtime is copied into `.kubb/`, so the generated code imports only `axios`.
|
|
6
6
|
|
|
7
7
|
## Setup
|
|
8
8
|
|
|
9
9
|
- Add `@kubb/plugin-ts` for the operation types, or `@kubb/plugin-zod` with `inferred: true`.
|
|
10
|
-
- Add `@kubb/plugin-zod`
|
|
11
|
-
- Install `axios` 1.20 or a later
|
|
10
|
+
- Add `@kubb/plugin-zod` and install `zod` v4 when you set `validator`. Generation fails without the plugin.
|
|
11
|
+
- Install `axios` 1.20 or a later 1.x release in the app that runs the generated code.
|
|
12
12
|
|
|
13
13
|
## Options worth knowing
|
|
14
14
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
15
|
+
| Option | Set it to |
|
|
16
|
+
| --------------------- | ------------------------------------------------------------------------------------------ |
|
|
17
|
+
| `baseURL` | The starting host. The spec's top-level `servers` URL is not used. |
|
|
18
|
+
| `validator` | `'zod'` to check response bodies, or `{ request, params, response }` per part. |
|
|
19
|
+
| `throwOnErrorDefault` | `false` to return non-2xx responses as values. |
|
|
20
|
+
| `returnType` | `'data'` to resolve to the success body instead of the full result. |
|
|
21
|
+
| `sdk` | Classes instead of functions. Leave it unset for the query plugins and `@kubb/plugin-mcp`. |
|
|
20
22
|
|
|
21
|
-
|
|
23
|
+
Next, [call operations](https://kubb.dev/extensions/kubb-labs/plugin-axios/guides/calling-operations), or see every option and its default in [Options](https://kubb.dev/extensions/kubb-labs/plugin-axios/options).
|
|
22
24
|
|
|
23
25
|
## Example
|
|
24
26
|
|
|
25
|
-
|
|
27
|
+
::code-group
|
|
26
28
|
|
|
27
29
|
```typescript [kubb.config.ts]
|
|
28
30
|
import { defineConfig } from 'kubb/config'
|
|
@@ -34,9 +36,25 @@ export default defineConfig({
|
|
|
34
36
|
input: './petStore.yaml',
|
|
35
37
|
output: { path: './src/gen' },
|
|
36
38
|
adapter: adapterOas({ integerType: 'number' }),
|
|
37
|
-
plugins: [
|
|
38
|
-
pluginTs(),
|
|
39
|
-
pluginAxios({ baseURL: 'https://petstore.swagger.io/v2' }),
|
|
40
|
-
],
|
|
39
|
+
plugins: [pluginTs(), pluginAxios({ baseURL: 'https://petstore.swagger.io/v2' })],
|
|
41
40
|
})
|
|
42
41
|
```
|
|
42
|
+
|
|
43
|
+
```typescript [src/app.ts]
|
|
44
|
+
import { getPetById } from './gen/clients/getPetById'
|
|
45
|
+
|
|
46
|
+
const { data } = await getPetById({ path: { petId: 1 } })
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
```text [Generated files]
|
|
50
|
+
src/gen/
|
|
51
|
+
├── .kubb/ # the runtime: client.ts, core.ts, config.ts, serializers/, ...
|
|
52
|
+
├── clients/
|
|
53
|
+
│ ├── getPetById.ts
|
|
54
|
+
│ └── index.ts
|
|
55
|
+
└── types/
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
::
|
|
59
|
+
|
|
60
|
+
With [`integerType: 'number'`](https://kubb.dev/extensions/kubb-labs/adapter-oas/options#integertype), an `int64` id such as `petId` is a `number`. With the default `bigint`, pass `1n`.
|
package/kubb-extension.json
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kubb/plugin-axios",
|
|
3
|
-
"version": "6.0.
|
|
3
|
+
"version": "6.0.4",
|
|
4
4
|
"description": "Generate a slim, type-safe HTTP client with Kubb based on axios.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"api-client",
|
|
@@ -83,8 +83,8 @@
|
|
|
83
83
|
"registry": "https://registry.npmjs.org/"
|
|
84
84
|
},
|
|
85
85
|
"dependencies": {
|
|
86
|
-
"@kubb/kit": "^5.
|
|
87
|
-
"@kubb/plugin-client": "^6.0.
|
|
86
|
+
"@kubb/kit": "^5.20.1",
|
|
87
|
+
"@kubb/plugin-client": "^6.0.4"
|
|
88
88
|
},
|
|
89
89
|
"devDependencies": {
|
|
90
90
|
"axios": "^1.21.1",
|
|
@@ -1,101 +0,0 @@
|
|
|
1
|
-
# Authenticate requests
|
|
2
|
-
|
|
3
|
-
Set an `auth` resolver on the generated client. Operations use the [security schemes](https://spec.openapis.org/oas/v3.1.0#security-scheme-object) declared in your OpenAPI spec. Requests remain unauthenticated until you provide credentials.
|
|
4
|
-
|
|
5
|
-
## Set the auth resolver
|
|
6
|
-
|
|
7
|
-
Set the resolver for all secured operations:
|
|
8
|
-
|
|
9
|
-
```typescript
|
|
10
|
-
import { client } from './gen/.kubb/client'
|
|
11
|
-
|
|
12
|
-
client.setConfig({
|
|
13
|
-
auth: () => localStorage.getItem('token') ?? undefined,
|
|
14
|
-
})
|
|
15
|
-
```
|
|
16
|
-
|
|
17
|
-
`auth` takes a token string or a function. The function can be async and returns a token, or `undefined` to skip that scheme. The runtime sends the first security requirement whose schemes all get a token. A requirement that needs an API key and a session cookie together sends both.
|
|
18
|
-
|
|
19
|
-
## Read the schemes of the spec
|
|
20
|
-
|
|
21
|
-
`.kubb/client.ts` exports the schemes of the spec by name as `securitySchemes`. A `mutualTLS` scheme is left out, because its credential is a client certificate in the TLS handshake, not a token the `auth` resolver can return. See [Use mutual TLS](https://kubb.dev/extensions/kubb-labs/plugin-axios/guides/authentication#use-mutual-tls). A generated operation points at its schemes there, and adds the scopes it needs:
|
|
22
|
-
|
|
23
|
-
```typescript
|
|
24
|
-
security: [{ ...securitySchemes.petstore_auth, scopes: ['write:pets'] }]
|
|
25
|
-
```
|
|
26
|
-
|
|
27
|
-
## Return the right token per scheme
|
|
28
|
-
|
|
29
|
-
Use the scheme passed to the resolver to select a credential:
|
|
30
|
-
|
|
31
|
-
```typescript
|
|
32
|
-
type Auth = {
|
|
33
|
-
type: 'http' | 'apiKey' | 'oauth2' | 'openIdConnect'
|
|
34
|
-
scheme?: 'bearer' | 'basic'
|
|
35
|
-
name?: string
|
|
36
|
-
in?: 'header' | 'query' | 'cookie'
|
|
37
|
-
}
|
|
38
|
-
```
|
|
39
|
-
|
|
40
|
-
The scheme decides where the runtime puts the token:
|
|
41
|
-
|
|
42
|
-
| Scheme in the spec | `Auth` object | Where the token goes |
|
|
43
|
-
| ------------------ | ---------------------------------------- | ------------------------------- |
|
|
44
|
-
| `http` bearer | `{ type: 'http', scheme: 'bearer' }` | `Authorization: Bearer <token>` |
|
|
45
|
-
| `http` basic | `{ type: 'http', scheme: 'basic' }` | `Authorization: Basic <token>` |
|
|
46
|
-
| `apiKey` header | `{ type: 'apiKey', name, in: 'header' }` | request header named `name` |
|
|
47
|
-
| `apiKey` query | `{ type: 'apiKey', name, in: 'query' }` | query parameter named `name` |
|
|
48
|
-
| `apiKey` cookie | `{ type: 'apiKey', name, in: 'cookie' }` | `Cookie` header |
|
|
49
|
-
| `oauth2` | `{ type: 'oauth2' }` | `Authorization: Bearer <token>` |
|
|
50
|
-
| `openIdConnect` | `{ type: 'openIdConnect' }` | `Authorization: Bearer <token>` |
|
|
51
|
-
|
|
52
|
-
> [!NOTE]
|
|
53
|
-
> For basic auth, return the raw `username:password` string. The runtime base64-encodes it and writes the `Basic` prefix, so you never build the header yourself.
|
|
54
|
-
|
|
55
|
-
When a spec mixes schemes, branch on the `Auth` object and return the matching credential:
|
|
56
|
-
|
|
57
|
-
```typescript
|
|
58
|
-
client.setConfig({
|
|
59
|
-
auth: (auth) => (auth.type === 'apiKey' ? apiKey : accessToken),
|
|
60
|
-
})
|
|
61
|
-
```
|
|
62
|
-
|
|
63
|
-
## Use a separate client per environment
|
|
64
|
-
|
|
65
|
-
To give each environment its own token, such as one per tenant in a multi-tenant app, build an isolated client with `createClient`:
|
|
66
|
-
|
|
67
|
-
```typescript
|
|
68
|
-
import { createClient } from './gen/.kubb/client'
|
|
69
|
-
|
|
70
|
-
const tenant = createClient({
|
|
71
|
-
baseURL: 'https://tenant.example.com',
|
|
72
|
-
auth: () => tenantToken,
|
|
73
|
-
})
|
|
74
|
-
|
|
75
|
-
const { data } = await getPetById({ path: { petId: 1 }, client: tenant })
|
|
76
|
-
```
|
|
77
|
-
|
|
78
|
-
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`.
|
|
79
|
-
|
|
80
|
-
To override the client for one request, pass `auth` on that single call, which suits a one-off token refresh. A header you set yourself always wins over the resolved token: client-level `headers`, or `headers` on a call to an operation that declares header parameters.
|
|
81
|
-
|
|
82
|
-
For authentication outside OpenAPI security schemes, use an async request interceptor to sign requests or supply custom headers.
|
|
83
|
-
|
|
84
|
-
## Use mutual TLS
|
|
85
|
-
|
|
86
|
-
For a `mutualTLS` scheme, give the axios instance the client certificate in Node.js. Every request then presents it:
|
|
87
|
-
|
|
88
|
-
```typescript
|
|
89
|
-
import { readFileSync } from 'node:fs'
|
|
90
|
-
import { Agent } from 'node:https'
|
|
91
|
-
import axios from 'axios'
|
|
92
|
-
import { client, createAxiosTransport } from './gen/.kubb/client'
|
|
93
|
-
|
|
94
|
-
const instance = axios.create({
|
|
95
|
-
httpsAgent: new Agent({ cert: readFileSync('client.crt'), key: readFileSync('client.key') }),
|
|
96
|
-
})
|
|
97
|
-
|
|
98
|
-
client.setConfig({ transport: createAxiosTransport(instance) })
|
|
99
|
-
```
|
|
100
|
-
|
|
101
|
-
In the browser, the browser picks the client certificate itself.
|