forked from openapi-ts/openapi-typescript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
638 lines (593 loc) · 18 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
// settings & const
const PATH_PARAM_RE = /\{[^{}]+\}/g;
const supportsRequestInitExt = () => {
return (
typeof process === "object" &&
Number.parseInt(process?.versions?.node?.substring(0, 2)) >= 18 &&
process.versions.undici
);
};
/**
* Returns a cheap, non-cryptographically-secure random ID
* Courtesy of @imranbarbhuiya (https://github.com/imranbarbhuiya)
*/
export function randomID() {
return Math.random().toString(36).slice(2, 11);
}
/**
* Create an openapi-fetch client.
* @type {import("./index.js").default}
*/
export default function createClient(clientOptions) {
let {
baseUrl = "",
Request: CustomRequest = globalThis.Request,
fetch: baseFetch = globalThis.fetch,
querySerializer: globalQuerySerializer,
bodySerializer: globalBodySerializer,
headers: baseHeaders,
requestInitExt = undefined,
...baseOptions
} = { ...clientOptions };
requestInitExt = supportsRequestInitExt() ? requestInitExt : undefined;
baseUrl = removeTrailingSlash(baseUrl);
const middlewares = [];
/**
* Per-request fetch (keeps settings created in createClient()
* @param {T} url
* @param {import('./index.js').FetchOptions<T>} fetchOptions
*/
async function coreFetch(schemaPath, fetchOptions) {
const {
baseUrl: localBaseUrl,
fetch = baseFetch,
Request = CustomRequest,
headers,
params = {},
parseAs = "json",
querySerializer: requestQuerySerializer,
bodySerializer = globalBodySerializer ?? defaultBodySerializer,
body,
...init
} = fetchOptions || {};
if (localBaseUrl) {
baseUrl = removeTrailingSlash(localBaseUrl);
}
let querySerializer =
typeof globalQuerySerializer === "function"
? globalQuerySerializer
: createQuerySerializer(globalQuerySerializer);
if (requestQuerySerializer) {
querySerializer =
typeof requestQuerySerializer === "function"
? requestQuerySerializer
: createQuerySerializer({
...(typeof globalQuerySerializer === "object" ? globalQuerySerializer : {}),
...requestQuerySerializer,
});
}
const serializedBody = body === undefined ? undefined : bodySerializer(body);
const defaultHeaders =
// with no body, we should not to set Content-Type
serializedBody === undefined ||
// if serialized body is FormData; browser will correctly set Content-Type & boundary expression
serializedBody instanceof FormData
? {}
: {
"Content-Type": "application/json",
};
const requestInit = {
redirect: "follow",
...baseOptions,
...init,
body: serializedBody,
headers: mergeHeaders(defaultHeaders, baseHeaders, headers, params.header),
};
let id;
let options;
let request = new CustomRequest(createFinalURL(schemaPath, { baseUrl, params, querySerializer }), requestInit);
let response;
/** Add custom parameters to Request object */
for (const key in init) {
if (!(key in request)) {
request[key] = init[key];
}
}
if (middlewares.length) {
id = randomID();
// middleware (request)
options = Object.freeze({
baseUrl,
fetch,
parseAs,
querySerializer,
bodySerializer,
});
for (const m of middlewares) {
if (m && typeof m === "object" && typeof m.onRequest === "function") {
const result = await m.onRequest({
request,
schemaPath,
params,
options,
id,
});
if (result) {
if (result instanceof CustomRequest) {
request = result;
} else if (result instanceof Response) {
response = result;
break;
} else {
throw new Error("onRequest: must return new Request() or Response() when modifying the request");
}
}
}
}
}
if (!response) {
// fetch!
try {
response = await fetch(request, requestInitExt);
} catch (error) {
let errorAfterMiddleware = error;
// middleware (error)
// execute in reverse-array order (first priority gets last transform)
if (middlewares.length) {
for (let i = middlewares.length - 1; i >= 0; i--) {
const m = middlewares[i];
if (m && typeof m === "object" && typeof m.onError === "function") {
const result = await m.onError({
request,
error: errorAfterMiddleware,
schemaPath,
params,
options,
id,
});
if (result) {
// if error is handled by returning a response, skip remaining middleware
if (result instanceof Response) {
errorAfterMiddleware = undefined;
response = result;
break;
}
if (result instanceof Error) {
errorAfterMiddleware = result;
continue;
}
throw new Error("onError: must return new Response() or instance of Error");
}
}
}
}
// rethrow error if not handled by middleware
if (errorAfterMiddleware) {
throw errorAfterMiddleware;
}
}
// middleware (response)
// execute in reverse-array order (first priority gets last transform)
if (middlewares.length) {
for (let i = middlewares.length - 1; i >= 0; i--) {
const m = middlewares[i];
if (m && typeof m === "object" && typeof m.onResponse === "function") {
const result = await m.onResponse({
request,
response,
schemaPath,
params,
options,
id,
});
if (result) {
if (!(result instanceof Response)) {
throw new Error("onResponse: must return new Response() when modifying the response");
}
response = result;
}
}
}
}
}
// handle empty content
if (response.status === 204 || response.headers.get("Content-Length") === "0") {
return response.ok ? { data: undefined, response } : { error: undefined, response };
}
// parse response (falling back to .text() when necessary)
if (response.ok) {
// if "stream", skip parsing entirely
if (parseAs === "stream") {
return { data: response.body, response };
}
return { data: await response[parseAs](), response };
}
// handle errors
let error = await response.text();
try {
error = JSON.parse(error); // attempt to parse as JSON
} catch {
// noop
}
return { error, response };
}
return {
request(method, url, init) {
return coreFetch(url, { ...init, method: method.toUpperCase() });
},
/** Call a GET endpoint */
GET(url, init) {
return coreFetch(url, { ...init, method: "GET" });
},
/** Call a PUT endpoint */
PUT(url, init) {
return coreFetch(url, { ...init, method: "PUT" });
},
/** Call a POST endpoint */
POST(url, init) {
return coreFetch(url, { ...init, method: "POST" });
},
/** Call a DELETE endpoint */
DELETE(url, init) {
return coreFetch(url, { ...init, method: "DELETE" });
},
/** Call a OPTIONS endpoint */
OPTIONS(url, init) {
return coreFetch(url, { ...init, method: "OPTIONS" });
},
/** Call a HEAD endpoint */
HEAD(url, init) {
return coreFetch(url, { ...init, method: "HEAD" });
},
/** Call a PATCH endpoint */
PATCH(url, init) {
return coreFetch(url, { ...init, method: "PATCH" });
},
/** Call a TRACE endpoint */
TRACE(url, init) {
return coreFetch(url, { ...init, method: "TRACE" });
},
/** Register middleware */
use(...middleware) {
for (const m of middleware) {
if (!m) {
continue;
}
if (typeof m !== "object" || !("onRequest" in m || "onResponse" in m || "onError" in m)) {
throw new Error("Middleware must be an object with one of `onRequest()`, `onResponse() or `onError()`");
}
middlewares.push(m);
}
},
/** Unregister middleware */
eject(...middleware) {
for (const m of middleware) {
const i = middlewares.indexOf(m);
if (i !== -1) {
middlewares.splice(i, 1);
}
}
},
};
}
class PathCallForwarder {
constructor(client, url) {
this.client = client;
this.url = url;
}
GET(init) {
return this.client.GET(this.url, init);
}
PUT(init) {
return this.client.PUT(this.url, init);
}
POST(init) {
return this.client.POST(this.url, init);
}
DELETE(init) {
return this.client.DELETE(this.url, init);
}
OPTIONS(init) {
return this.client.OPTIONS(this.url, init);
}
HEAD(init) {
return this.client.HEAD(this.url, init);
}
PATCH(init) {
return this.client.PATCH(this.url, init);
}
TRACE(init) {
return this.client.TRACE(this.url, init);
}
}
class PathClientProxyHandler {
constructor() {
this.client = null;
}
// Assume the property is an URL.
get(coreClient, url) {
const forwarder = new PathCallForwarder(coreClient, url);
this.client[url] = forwarder;
return forwarder;
}
}
/**
* Wrap openapi-fetch client to support a path based API.
* @type {import("./index.js").wrapAsPathBasedClient}
*/
export function wrapAsPathBasedClient(coreClient) {
const handler = new PathClientProxyHandler();
const proxy = new Proxy(coreClient, handler);
// Put the proxy on the prototype chain of the actual client.
// This means if we do not have a memoized PathCallForwarder,
// we fall back to the proxy to synthesize it.
// However, the proxy itself is not on the hot-path (if we fetch the same
// endpoint multiple times, only the first call will hit the proxy).
function Client() {}
Client.prototype = proxy;
const client = new Client();
// Feed the client back to the proxy handler so it can store the generated
// PathCallForwarder.
handler.client = client;
return client;
}
/**
* Convenience method to an openapi-fetch path based client.
* Strictly equivalent to `wrapAsPathBasedClient(createClient(...))`.
* @type {import("./index.js").createPathBasedClient}
*/
export function createPathBasedClient(clientOptions) {
return wrapAsPathBasedClient(createClient(clientOptions));
}
// utils
/**
* Serialize primitive param values
* @type {import("./index.js").serializePrimitiveParam}
*/
export function serializePrimitiveParam(name, value, options) {
if (value === undefined || value === null) {
return "";
}
if (typeof value === "object") {
throw new Error(
"Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.",
);
}
return `${name}=${options?.allowReserved === true ? value : encodeURIComponent(value)}`;
}
/**
* Serialize object param (shallow only)
* @type {import("./index.js").serializeObjectParam}
*/
export function serializeObjectParam(name, value, options) {
if (!value || typeof value !== "object") {
return "";
}
const values = [];
const joiner =
{
simple: ",",
label: ".",
matrix: ";",
}[options.style] || "&";
// explode: false
if (options.style !== "deepObject" && options.explode === false) {
for (const k in value) {
values.push(k, options.allowReserved === true ? value[k] : encodeURIComponent(value[k]));
}
const final = values.join(","); // note: values are always joined by comma in explode: false (but joiner can prefix)
switch (options.style) {
case "form": {
return `${name}=${final}`;
}
case "label": {
return `.${final}`;
}
case "matrix": {
return `;${name}=${final}`;
}
default: {
return final;
}
}
}
// explode: true
for (const k in value) {
const finalName = options.style === "deepObject" ? `${name}[${k}]` : k;
values.push(serializePrimitiveParam(finalName, value[k], options));
}
const final = values.join(joiner);
return options.style === "label" || options.style === "matrix" ? `${joiner}${final}` : final;
}
/**
* Serialize array param (shallow only)
* @type {import("./index.js").serializeArrayParam}
*/
export function serializeArrayParam(name, value, options) {
if (!Array.isArray(value)) {
return "";
}
// explode: false
if (options.explode === false) {
const joiner = { form: ",", spaceDelimited: "%20", pipeDelimited: "|" }[options.style] || ","; // note: for arrays, joiners vary wildly based on style + explode behavior
const final = (options.allowReserved === true ? value : value.map((v) => encodeURIComponent(v))).join(joiner);
switch (options.style) {
case "simple": {
return final;
}
case "label": {
return `.${final}`;
}
case "matrix": {
return `;${name}=${final}`;
}
// case "spaceDelimited":
// case "pipeDelimited":
default: {
return `${name}=${final}`;
}
}
}
// explode: true
const joiner = { simple: ",", label: ".", matrix: ";" }[options.style] || "&";
const values = [];
for (const v of value) {
if (options.style === "simple" || options.style === "label") {
values.push(options.allowReserved === true ? v : encodeURIComponent(v));
} else {
values.push(serializePrimitiveParam(name, v, options));
}
}
return options.style === "label" || options.style === "matrix"
? `${joiner}${values.join(joiner)}`
: values.join(joiner);
}
/**
* Serialize query params to string
* @type {import("./index.js").createQuerySerializer}
*/
export function createQuerySerializer(options) {
return function querySerializer(queryParams) {
const search = [];
if (queryParams && typeof queryParams === "object") {
for (const name in queryParams) {
const value = queryParams[name];
if (value === undefined || value === null) {
continue;
}
if (Array.isArray(value)) {
if (value.length === 0) {
continue;
}
search.push(
serializeArrayParam(name, value, {
style: "form",
explode: true,
...options?.array,
allowReserved: options?.allowReserved || false,
}),
);
continue;
}
if (typeof value === "object") {
search.push(
serializeObjectParam(name, value, {
style: "deepObject",
explode: true,
...options?.object,
allowReserved: options?.allowReserved || false,
}),
);
continue;
}
search.push(serializePrimitiveParam(name, value, options));
}
}
return search.join("&");
};
}
/**
* Handle different OpenAPI 3.x serialization styles
* @type {import("./index.js").defaultPathSerializer}
* @see https://swagger.io/docs/specification/serialization/#path
*/
export function defaultPathSerializer(pathname, pathParams) {
let nextURL = pathname;
for (const match of pathname.match(PATH_PARAM_RE) ?? []) {
let name = match.substring(1, match.length - 1);
let explode = false;
let style = "simple";
if (name.endsWith("*")) {
explode = true;
name = name.substring(0, name.length - 1);
}
if (name.startsWith(".")) {
style = "label";
name = name.substring(1);
} else if (name.startsWith(";")) {
style = "matrix";
name = name.substring(1);
}
if (!pathParams || pathParams[name] === undefined || pathParams[name] === null) {
continue;
}
const value = pathParams[name];
if (Array.isArray(value)) {
nextURL = nextURL.replace(match, serializeArrayParam(name, value, { style, explode }));
continue;
}
if (typeof value === "object") {
nextURL = nextURL.replace(match, serializeObjectParam(name, value, { style, explode }));
continue;
}
if (style === "matrix") {
nextURL = nextURL.replace(match, `;${serializePrimitiveParam(name, value)}`);
continue;
}
nextURL = nextURL.replace(match, style === "label" ? `.${encodeURIComponent(value)}` : encodeURIComponent(value));
}
return nextURL;
}
/**
* Serialize body object to string
* @type {import("./index.js").defaultBodySerializer}
*/
export function defaultBodySerializer(body) {
if (body instanceof FormData) {
return body;
}
return JSON.stringify(body);
}
/**
* Construct URL string from baseUrl and handle path and query params
* @type {import("./index.js").createFinalURL}
*/
export function createFinalURL(pathname, options) {
let finalURL = `${options.baseUrl}${pathname}`;
if (options.params?.path) {
finalURL = defaultPathSerializer(finalURL, options.params.path);
}
let search = options.querySerializer(options.params.query ?? {});
if (search.startsWith("?")) {
search = search.substring(1);
}
if (search) {
finalURL += `?${search}`;
}
return finalURL;
}
/**
* Merge headers a and b, with b taking priority
* @type {import("./index.js").mergeHeaders}
*/
export function mergeHeaders(...allHeaders) {
const finalHeaders = new Headers();
for (const h of allHeaders) {
if (!h || typeof h !== "object") {
continue;
}
const iterator = h instanceof Headers ? h.entries() : Object.entries(h);
for (const [k, v] of iterator) {
if (v === null) {
finalHeaders.delete(k);
} else if (Array.isArray(v)) {
for (const v2 of v) {
finalHeaders.append(k, v2);
}
} else if (v !== undefined) {
finalHeaders.set(k, v);
}
}
}
return finalHeaders;
}
/**
* Remove trailing slash from url
* @type {import("./index.js").removeTrailingSlash}
*/
export function removeTrailingSlash(url) {
if (url.endsWith("/")) {
return url.substring(0, url.length - 1);
}
return url;
}