@@ -5,10 +5,255 @@ description: openapi-fetch API
5
5
6
6
# API
7
7
8
- <img src =" /assets/openapi-ts.svg " alt =" openapi-typescript " width =" 200 " height =" 40 " />
8
+ ## createClient
9
+
10
+ ** createClient** 接受以下选项,这些选项设置所有后续 fetch 调用的默认设置。
11
+
12
+ ``` ts
13
+ createClient <paths >(options );
14
+ ```
15
+
16
+ | 名称 | 类型 | 描述 |
17
+ | :---------------- | :-------------- | :------------------------------------------------------------------------------------------------------------------------------------------ |
18
+ | ` baseUrl ` | ` string ` | 使用此选项为所有 fetch URL 添加前缀(例如 ` "https://myapi.dev/v1/" ` ) |
19
+ | ` fetch ` | ` fetch ` | 用于请求的 Fetch 实例(默认值:` globalThis.fetch ` ) |
20
+ | ` querySerializer ` | QuerySerializer | (可选) 提供一个 [ querySerializer] ( #queryserializer ) |
21
+ | ` bodySerializer ` | BodySerializer | (可选) 提供一个 [ bodySerializer] ( #bodyserializer ) |
22
+ | (Fetch 选项) | | 任何有效的 fetch 选项(` headers ` 、` mode ` 、` cache ` 、` signal ` 等)([ 文档] ( https://developer.mozilla.org/en-US/docs/Web/API/fetch#options ) ) |
23
+
24
+ ## Fetch 选项
25
+
26
+ 以下选项适用于所有请求方法(` .GET() ` 、` .POST() ` 等)。
27
+
28
+ ``` ts
29
+ client .GET (" /my-url" , options );
30
+ ```
31
+
32
+ | 名称 | 类型 | 描述 |
33
+ | :---------------- | :---------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
34
+ | ` params ` | ParamsObject | [ path] ( https://swagger.io/specification/#parameter-locations ) 和 [ query] ( https://swagger.io/specification/#parameter-locations ) 参数。 |
35
+ | ` body ` | ` { [name]:value } ` | [ requestBody] ( https://spec.openapis.org/oas/latest.html#request-body-object ) 数据。 |
36
+ | ` querySerializer ` | QuerySerializer | (可选) 提供一个 [ querySerializer] ( #queryserializer ) |
37
+ | ` bodySerializer ` | BodySerializer | (可选) 提供一个 [ bodySerializer] ( #bodyserializer ) |
38
+ | ` parseAs ` | ` "json" ` \| ` "text" ` \| ` "arrayBuffer" ` \| ` "blob" ` \| ` "stream" ` | (可选) 使用 [ 内置实例方法] ( https://developer.mozilla.org/en-US/docs/Web/API/Response#instance_methods ) 解析响应(默认值: ` "json" ` )。` "stream" ` 跳过解析,直接返回原始流。 |
39
+ | ` fetch ` | ` fetch ` | 用于请求的 Fetch 实例(默认:` createClient ` 的 fetch) |
40
+ | ` middleware ` | ` Middleware[] ` | [ 查看文档] ( /openapi-fetch/middleware-auth ) |
41
+ | (Fetch 选项) | | 任何有效的 fetch 选项(` headers ` 、` mode ` 、` cache ` 、` signal ` 等)([ 文档] ( https://developer.mozilla.org/en-US/docs/Web/API/fetch#options ) ) |
42
+
43
+ ## querySerializer
44
+
45
+ OpenAPI 支持[ 不同的对象和数组序列化方式] ( https://swagger.io/docs/specification/serialization/#query ) 。默认情况下,此库使用 ` style: "form", explode: true ` 序列化数组,使用 ` style: "deepObject", explode: true ` 序列化对象,但你可以使用 ` querySerializer ` 选项自定义此行为(在 ` createClient() ` 上控制每个请求,或在单个请求上为一个请求控制)。
46
+
47
+ ### 对象语法
48
+
49
+ openapi-fetch 提供了常见的序列化方法:
50
+
51
+ | 选项 | 类型 | 描述 |
52
+ | :------------ | :---------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------- |
53
+ | ` array ` | SerializerOptions | 设置数组的 ` style ` 和 ` explode ` ([ 文档] ( https://swagger.io/docs/specification/serialization/#query ) )。默认值:` { style: "form", explode: true } ` 。 |
54
+ | ` object ` | SerializerOptions | 设置对象的 ` style ` 和 ` explode ` ([ 文档] ( https://swagger.io/docs/specification/serialization/#query ) )。默认值:` { style: "deepObject", explode: true } ` 。 |
55
+ | ` allowReserved ` | ` boolean ` | 设置为 ` true ` 以跳过 URL 编码(⚠️ 可能会破坏请求)([ 文档] ( https://swagger.io/docs/specification/serialization/#query ) )。默认值:` false ` 。 |
56
+
57
+ ``` ts
58
+ const client = createClient ({
59
+ querySerializer: {
60
+ array: {
61
+ style: " pipeDelimited" , // "form" (默认) | "spaceDelimited" | "pipeDelimited"
62
+ explode: true ,
63
+ },
64
+ object: {
65
+ style: " form" , // "form" | "deepObject" (默认)
66
+ explode: true ,
67
+ },
68
+ },
69
+ });
70
+ ```
71
+
72
+ #### 数组样式
73
+
74
+ | 样式 | 数组 ` id = [3, 4, 5] ` |
75
+ | :--------------------------- | :---------------------- |
76
+ | form | ` /users?id=3,4,5 ` |
77
+ | ** form (exploded, 默认)** | ` /users?id=3&id=4&id=5 ` |
78
+ | spaceDelimited | ` /users?id=3%204%205 ` |
79
+ | spaceDelimited (exploded) | ` /users?id=3&id=4&id=5 ` |
80
+ | pipeDelimited | ` /users?id=3\|4\|5 ` |
81
+ | pipeDelimited (exploded) | ` /users?id=3&id=4&id=5 ` |
82
+
83
+ #### 对象样式
84
+
85
+ | 样式 | 对象 ` id = {"role": "admin", "firstName": "Alex"} ` |
86
+ | :----------------------- | :--------------------------------------------------- |
87
+ | form | ` /users?id=role,admin,firstName,Alex ` |
88
+ | form (exploded) | ` /users?role=admin&firstName=Alex ` |
89
+ | ** deepObject (默认)** | ` /users?id[role]=admin&id[firstName]=Alex ` |
90
+
91
+ ::: tip
92
+
93
+ 对于 ** deepObject** 这种复杂的对象结构, 无论你设置 ` explode: true ` 还是 ` explode: false ` ,它都会生成相同的输出。
94
+
95
+ :::
96
+
97
+ ### 替代函数语法
98
+
99
+ 有时候你的后端不使用标准的序列化方法之一,此时你可以将一个函数传递给 ` querySerializer ` ,自己序列化整个字符串。如果你处理你的参数中的深度嵌套对象和数组,也需要使用此方法:
100
+
101
+ ``` ts
102
+ const client = createClient ({
103
+ querySerializer(queryParams
104
+
105
+ ) {
106
+ const search = [];
107
+ for (const name in queryParams ) {
108
+ const value = queryParams [name ];
109
+ if (Array .isArray (value )) {
110
+ for (const item of value ) {
111
+ s .push (` ${name }[]=${encodeURIComponent (item )} ` );
112
+ }
113
+ } else {
114
+ s .push (` ${name }=${encodeURLComponent (value )} ` );
115
+ }
116
+ }
117
+ return search .join (" ," ); // ?tags[]=food,tags[]=california,tags[]=healthy
118
+ },
119
+ });
120
+ ```
9
121
10
122
::: warning
11
123
12
- This article is a stub. Please help [ expand it ] ( https://github.com/drwpow/openapi-typescript/tree/main/docs/zh/ ) !
124
+ 当自己序列化时,字符串将保持与作者编写的内容完全一样,因此你必须调用 [ encodeURI ] ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI ) 或 [ encodeURIComponent ] ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent ) 来转义特殊字符。
13
125
14
126
:::
127
+
128
+ ## bodySerializer
129
+
130
+ 类似于 [ querySerializer] ( #queryserializer ) ,bodySerializer 允许你自定义 requestBody 在你不想要默认 [ JSON.stringify()] ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify ) 行为的情况下的序列化方式。当使用 ` multipart/form-data ` 时可能会用到:
131
+
132
+ ``` ts
133
+ const { data, error } = await client .PUT (" /submit" , {
134
+ body: {
135
+ name: " " ,
136
+ query: { version: 2 },
137
+ },
138
+ bodySerializer(body ) {
139
+ const fd = new FormData ();
140
+ for (const name in body ) {
141
+ fd .append (name , body [name ]);
142
+ }
143
+ return fd ;
144
+ },
145
+ });
146
+ ```
147
+
148
+ ## 路径序列化
149
+
150
+ openapi-fetch 支持根据你的 OpenAPI 架构中的具体格式自动进行[ 路径序列化] ( https://swagger.io/docs/specification/serialization/#path ) :
151
+
152
+ | 模板 | 样式 | 基础类型 ` id = 5 ` | 数组 ` id = [3, 4, 5] ` | 对象 ` id = {"role": "admin", "firstName": "Alex"} ` |
153
+ | :---------------- | :------------------- | :--------------- | :----------------------- | :--------------------------------------------------- |
154
+ | ** ` /users/{id} ` ** | ** simple (默认)** | ** ` /users/5 ` ** | ** ` /users/3,4,5 ` ** | ** ` /users/role,admin,firstName,Alex ` ** |
155
+ | ` /users/{id*} ` | simple (爆炸) | ` /users/5 ` | ` /users/3,4,5 ` | ` /users/role=admin,firstName=Alex ` |
156
+ | ` /users/{.id} ` | label | ` /users/.5 ` | ` /users/.3,4,5 ` | ` /users/.role,admin,firstName,Alex ` |
157
+ | ` /users/{.id*} ` | label (爆炸) | ` /users/.5 ` | ` /users/.3.4.5 ` | ` /users/.role=admin.firstName=Alex ` |
158
+ | ` /users/{;id} ` | matrix | ` /users/;id=5 ` | ` /users/;id=3,4,5 ` | ` /users/;id=role,admin,firstName,Alex ` |
159
+ | ` /users/{;id*} ` | matrix (爆炸) | ` /users/;id=5 ` | ` /users/;id=3;id=4;id=5 ` | ` /users/;role=admin;firstName=Alex ` |
160
+
161
+ ## 中间件
162
+
163
+ 中间件是具有 ` onRequest() ` 和 ` onResponse() ` 回调的对象,可以观察和修改请求和响应。
164
+
165
+ ``` ts
166
+ import createClient from " openapi-fetch" ;
167
+ import type { paths } from " ./api/v1" ;
168
+
169
+ const myMiddleware: Middleware = {
170
+ async onRequest(req , options ) {
171
+ // 设置 "foo" 标头
172
+ req .headers .set (" foo" , " bar" );
173
+ return req ;
174
+ },
175
+ async onResponse(res , options ) {
176
+ const { body, ... resOptions } = res ;
177
+ // 更改响应的状态
178
+ return new Response (body , { ... resOptions , status: 200 });
179
+ },
180
+ };
181
+
182
+ const client = createClient <paths >({ baseUrl: " https://myapi.dev/v1/" });
183
+
184
+ // 注册中间件
185
+ client .use (myMiddleware );
186
+ ```
187
+
188
+ ### onRequest
189
+
190
+ ``` ts
191
+ onRequest (req , options ) {
192
+ // …
193
+ }
194
+ ```
195
+
196
+ ` onRequest() ` 接受 2 个参数:
197
+
198
+ | 名称 | 类型 | 描述 |
199
+ | :-------- | :-----------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
200
+ | ` req ` | ` MiddlewareRequest ` | 带有 ` schemaPath ` (OpenAPI 路径名)和 ` params ` ([ params] ( /openapi-fetch/api#fetch-options ) 对象)的标准 [ Request] ( https://developer.mozilla.org/en-US/docs/Web/API/Request ) |
201
+ | ` options ` | ` MergedOptions ` | [ createClient] ( /openapi-fetch/api#create-client ) 选项 + [ fetch 覆盖] ( /openapi-fetch/api#fetch-options ) 的组合 |
202
+
203
+ 它期望的结果要么是:
204
+
205
+ - ** 如果修改请求:** 一个 [ Request] ( https://developer.mozilla.org/en-US/docs/Web/API/Request )
206
+ - ** 如果不修改:** ` undefined ` (void)
207
+
208
+ ### onResponse
209
+
210
+ ``` ts
211
+ onResponse (res , options ) {
212
+ // …
213
+ }
214
+ ```
215
+
216
+ ` onResponse() ` 也接受 2 个参数:
217
+
218
+ | 名称 | 类型 | 描述 |
219
+ | :-------- | :----------------: | :------------------------------------------------- |
220
+ | ` req ` | ` MiddlewareRequest ` | 一个标准的 [ Response] ( https://developer.mozilla.org/en-US/docs/Web/API/Response ) 。 |
221
+ | ` options ` | ` MergedOptions ` | [ createClient] ( /openapi-fetch/api#create-client ) 选项 + [ fetch 覆盖] ( /openapi-fetch/api#fetch-options ) 的组合 |
222
+
223
+ 它期望的结果要么是:
224
+
225
+ - ** 如果修改响应:** 一个 [ Response] ( https://developer.mozilla.org/en-US/docs/Web/API/Response )
226
+ - ** 如果不修改:** ` undefined ` (void)
227
+
228
+ ### 跳过
229
+
230
+ 如果你想要在某些条件下跳过中间件,只需尽早 ` return ` :
231
+
232
+ ``` ts
233
+ onRequest (req ) {
234
+ if (req .schemaPath !== " /projects/{project_id}" ) {
235
+ return undefined ;
236
+ }
237
+ // …
238
+ }
239
+ ```
240
+
241
+ 这将保持请求/响应不变,并将其传递给下一个中间件处理程序(如果有的话)。不需要内部回调或观察器库。
242
+
243
+ ### 移除中间件
244
+
245
+ 要移除中间件,请调用 ` client.eject(middleware) ` :
246
+
247
+ ``` ts{9}
248
+ const myMiddleware = {
249
+ // …
250
+ };
251
+
252
+ // 注册中间件
253
+ client.use(myMiddleware);
254
+
255
+ // 删除中间件
256
+ client.eject(myMiddleware);
257
+ ```
258
+
259
+ 有关附加指南和示例,请参阅 [ 中间件 & 身份认证] ( /zh/openapi-fetch/middleware-auth )
0 commit comments