-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
533 lines (494 loc) · 13.5 KB
/
index.ts
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
/* Architecture Note #1: Generating the SDK
Most SDK from API generator are very opinionated on how the
users will use it. We wanted to have a very simple API to
be able to customize it at will.
This file simply eats an OpenAPI file and generate
the SDK to avoid boilerplate code.
A small article about why and how to do that:
https://insertafter.com/en/blog/considerations_for_generating_api_clients.html
*/
/**
* @module openapi-ts-sdk-builder
*/
import camelCase from 'camelcase';
import SwaggerParser from '@apidevtools/swagger-parser';
import { generateOpenAPITypes, toSource } from 'schema2dts';
import type { OpenAPIV3 } from 'openapi-types';
const URI_PARAMETERS = ['path', 'query'];
function upperCamelCase(s: string): string {
return s[0].toUpperCase() + s.slice(1);
}
function dereference<T>(
$refs: SwaggerParser.$Refs,
maybeARef: OpenAPIV3.ReferenceObject | T,
) {
return (maybeARef as OpenAPIV3.ReferenceObject).$ref
? ($refs.get((maybeARef as OpenAPIV3.ReferenceObject).$ref) as Exclude<
typeof maybeARef,
OpenAPIV3.ReferenceObject
>)
: (maybeARef as Exclude<typeof maybeARef, OpenAPIV3.ReferenceObject>);
}
function buildParameterJSDOC(
$refs: SwaggerParser.$Refs,
parameter: OpenAPIV3.ParameterObject,
): string {
const schema = parameter.schema
? dereference($refs, parameter.schema)
: undefined;
return `
* @param {${
schema
? schema.oneOf
? [
...new Set(
(
(parameter.schema as OpenAPIV3.BaseSchemaObject).oneOf || []
).map((s) => {
const dereferencedSchema = dereference($refs, s);
return dereferencedSchema.type;
}),
),
].join('|')
: schema?.type
: 'any'
}} ${parameter.required ? `` : `[`}parameters.${camelCase(parameter.name)}${
parameter.required ? `` : `]`
}${
parameter.description
? `
* ${parameter.description}`
: ''
}`;
}
/**
* Build a JS SDK from an OpenAPI file
*
* @async
* @method generateSDKFromOpenAPI
* @param {string} openAPIContent
* @param {Object} options
* @param {string} options.sdkVersion
* The SDK version
* @param {string} [options.sdkName]
* The SDK name (default to API)
* @param {string[]} [options.ignoredParametersNames]
* Provide a list of parameters to ignore
* @param {string[]} [options.undocumentedParametersNames]
* Provide a list of parameters to keep undocumented
* @param {Object} [typeOptions]
* Options to be passed to the type generator
* @return {Promise<string>} The SDK JS code
*/
export async function generateSDKFromOpenAPI(
openAPIContent: string,
{
sdkVersion,
sdkName = 'API',
ignoredParametersNames = [],
undocumentedParametersNames = [],
}: {
sdkVersion: string;
sdkName?: string;
ignoredParametersNames?: string[];
undocumentedParametersNames?: string[];
},
typeOptions: Parameters<typeof generateOpenAPITypes>[1] = {
exportNamespaces: true,
generateRealEnums: true,
tuplesFromFixedArraysLengthLimit: 2,
},
): Promise<string> {
const adaptedTypeOptions = {
baseName: sdkName + 'Types',
...typeOptions,
};
const API = JSON.parse(openAPIContent);
const $refs = await SwaggerParser.resolve(API as never);
const operations = getOpenAPIOperations(API);
const content = `/* tslint:disable */
/* eslint-disable */
// WARNING: This file is automatically generated
// do not change it in place it would be overridden
// by the next build
type Writeable<T extends { [x: string]: unknown }> = {
[P in keyof T]: T[P];
};
export type Method = 'options' | 'get' | 'head' |'post' | 'put' | 'patch' | 'delete';
export type QueryParams = {
[name: string]: string | number | string[] | number[] | boolean | undefined;
};
export type Headers = Record<string, string>;
export type URIData = {
path: string;
params: QueryParams;
};
export type HTTPRequest<T> = URIData & {
method: Method;
headers: Headers;
body: T;
};
export type HTTPResponse<T> = {
status: number;
headers: Headers;
body: T;
};
export type RequestExecutor<O, T = unknown, U = unknown> = (
request: HTTPRequest<T>,
operationId: string,
options: O,
) => Promise<HTTPResponse<U>>;
${toSource(await generateOpenAPITypes(API, adaptedTypeOptions))}
/**
* ${API.info.description}
* @module API
* @version ${API.info.version}
*/
const API = {${operations
.map(
({ operationId }) => `
${operationId},`,
)
.join('')}
};
export const APIURIBuilders = {${operations
.map(
({ operationId }) => `
${operationId}: build${upperCamelCase(operationId as string)}URI,`,
)
.join('')}
};
export const APIMethods = {${operations
.map(
({ operationId, method }) => `
${operationId}: '${method}',`,
)
.join('')}
} as const;
export const APIStatuses = {${operations
.map(
({ operationId, responses }) => `
${operationId}: [${Object.keys(responses || { default: '' })
.map((code) => (code !== 'default' ? parseInt(code, 10) : `"${code}"`))
.join(', ')}],`,
)
.join('')}
} as const;
export const APIInputBuilders = {${operations
.map(
({ operationId }) => `
${operationId}: build${upperCamelCase(operationId as string)}Input,`,
)
.join('')}
};
${operations
.map((operation) => {
const { path, operationId, parameters, requestBody } = operation;
const dereferencedParameters = (parameters || [])
.map((parameter) => dereference($refs, parameter))
.filter((p) => !ignoredParametersNames.includes(p.name));
const uriParameters = dereferencedParameters.filter((p) =>
URI_PARAMETERS.includes(p.in),
);
const nonURIParameters = dereferencedParameters.filter(
(p) => !URI_PARAMETERS.includes(p.in),
);
return `
/**
* Build the "${operation.operationId}" URI parameters$
* @return {Object}
* The object describing the built URI
* @param {Object} parameters
* The parameters provided to build the URI (destructured)${uriParameters
.filter((p) => !undocumentedParametersNames.includes(p.name))
.map(buildParameterJSDOC.bind(null, $refs))}
*/
function build${upperCamelCase(operationId as string)}URI(${
uriParameters.length
? `
{${uriParameters
.map(
(parameter) => `
${camelCase(parameter.name)},`,
)
.join('')}
} : ${
uriParameters.length
? `Pick<${adaptedTypeOptions.baseName}.${upperCamelCase(
operationId as string,
)}.Input,${uriParameters
.map(
(parameter) => `
'${camelCase(parameter.name)}'`,
)
.join('|')}
>`
: 'Record<string, never>'
}`
: `
_: unknown`
},
) : URIData {${uriParameters
.map((parameter) =>
parameter.required
? `
if(${camelCase(parameter.name)} == null) {
throw new Error('Missing required parameter: ${camelCase(
parameter.name,
)}. Value : ' + ${camelCase(parameter.name)});
}`
: '',
)
.join('')}
const __pathParts = [${path
.split('/')
.filter((identity) => identity)
.map((part) => {
const result = /^{([a-z0-9]+)}$/gi.exec(part);
if (result) {
return `
${camelCase(result[1])},`;
}
return `
'${part}',`;
})
.join('')}
];
const __qs = cleanQuery({${dereferencedParameters
.filter((p) => 'query' === p.in)
.map(
(parameter) => `
${parameter.name}: ${camelCase(parameter.name)}${
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(parameter as any).ordered ? '.sort(sortMultipleQuery)' : ''
},`,
)
.join('')}
});
return {
path: __pathParts.join('/'),
params: __qs,
};
}
/**
* Build all the "${operation.operationId as string}" parameters
* @return {Object}
* The object describing the built parameters${
requestBody
? `
* @param {Object} body
* The request body`
: ''
}
* @param {Object} parameters
* The parameters provided to build them (destructured)${dereferencedParameters
.filter((p) => !undocumentedParametersNames.includes(p.name))
.map(buildParameterJSDOC.bind(null, $refs))}
*/
function build${upperCamelCase(operationId as string)}Input(${
requestBody || (dereferencedParameters && dereferencedParameters.length)
? `
{${
requestBody
? `
body,`
: ''
}${dereferencedParameters
.map(
(parameter) => `
${camelCase(parameter.name)},`,
)
.join('')}
} : ${adaptedTypeOptions.baseName}.${upperCamelCase(
operationId as string,
)}.Input`
: `
_: unknown`
},
) : HTTPRequest<${
requestBody
? `${adaptedTypeOptions.baseName}.${upperCamelCase(
operationId as string,
)}.Input['body']`
: 'undefined'
}> {
${nonURIParameters
.map((parameter) =>
parameter.required
? `
if( ${camelCase(parameter.name)} == null) {
throw new Error('Missing required parameter : ${camelCase(
parameter.name,
)}. Value : ' + ${camelCase(parameter.name)});
}
`
: '',
)
.join('')}
const __method = APIMethods.${operationId};
const __uriData = build${upperCamelCase(
operationId as string,
)}URI({${uriParameters
.map(
(parameter) => `
${camelCase(parameter.name)},`,
)
.join('')}
});
return {
method: __method,
...__uriData,
headers: cleanHeaders({
'X-API-Version': '${API.info.version}',${
sdkVersion
? `
'X-SDK-Version': '${sdkVersion}',`
: ''
}${dereferencedParameters
.filter((p) => 'header' === p.in)
.filter((p) => !['X-API-Version', 'X-SDK-Version'].includes(p.name))
.map((parameter) => {
const schema = parameter.schema
? dereference($refs, parameter.schema)
: undefined;
return `
'${parameter.name}': ${camelCase(parameter.name)}${
schema?.type !== 'string' ? '.toString()' : ''
},`;
})
.join('')}
}),
body: ${requestBody ? 'body' : 'undefined'},
};
}
/**
* ${operation.summary}
* @return {Object}
* The object describing the built parameters
* @param {Function} executeRequest
* An asynchronous function to effectively run the request
* @param {Object} parameters
* The parameters provided to build them (destructured)${
requestBody
? `
* @param {Object} parameters.body
* The request body`
: ''
}${dereferencedParameters
.filter((p) => !undocumentedParametersNames.includes(p.name))
.map(buildParameterJSDOC.bind(null, $refs))}
* @param {Object} [options]
* Eventual options for the request execution
* @return {Object}
* The HTTP response
*/
async function ${operationId}<O>(
executeRequest: RequestExecutor<O>,${
requestBody || (dereferencedParameters && dereferencedParameters.length)
? `
{${
requestBody
? `
body,`
: ''
}${dereferencedParameters
.map(
(parameter) => `
${camelCase(parameter.name)},`,
)
.join('')}
} : ${adaptedTypeOptions.baseName}.${upperCamelCase(
operationId as string,
)}.Input`
: `
_: unknown`
},
options: O,
) : Promise<Writeable<${adaptedTypeOptions.baseName}.${upperCamelCase(
operationId as string,
)}.Output>> {
const httpRequest = build${upperCamelCase(operationId as string)}Input({${
requestBody
? `
body,`
: ''
}${dereferencedParameters
.map(
(parameter) => `
${camelCase(parameter.name)},`,
)
.join('')}
});
return (await executeRequest(
httpRequest,
"${operationId as string}",
options,
)) as ${adaptedTypeOptions.baseName}.${upperCamelCase(
operationId as string,
)}.Output;
}`;
})
.join('\n')}
function cleanQuery(query: QueryParams): QueryParams {
return Object.keys(query)
.filter(key => "undefined" !== typeof query[key])
.filter(key => !(query[key] instanceof Array) || 0 !== (query[key] as any[]).length)
.reduce((newQuery, key) => {
newQuery[key] = query[key];
return newQuery;
}, {} as QueryParams);
}
export function cleanHeaders(headers: Headers): Headers {
return Object.keys(headers)
.filter(key => "undefined" !== typeof headers[key])
.reduce((newHeaders, key) => {
newHeaders[key] = headers[key];
return newHeaders;
}, {} as Headers);
}
export function sortMultipleQuery(a: number, b: number): number {
return a > b ? 1 : -1;
}
export default API;
`;
return content;
}
// Code duplicated from https://github.com/nfroidure/whook/blob/master/packages/whook-http-router/src/libs/openAPIUtils.ts
// TODO: Use it back when it gets strict TS ready
export const OPEN_API_METHODS = [
'options',
'head',
'get',
'put',
'post',
'patch',
'delete',
'trace',
];
export type WhookRawOperation<T = Record<string, unknown>> =
OpenAPIV3.OperationObject & {
path: string;
method: string;
'x-whook'?: T;
};
export function getOpenAPIOperations<T = Record<string, unknown>>(
API: OpenAPIV3.Document,
): WhookRawOperation<T>[] {
return Object.keys(API.paths).reduce<WhookRawOperation<T>[]>(
(operations, path) =>
Object.keys(API.paths[path] || {})
.filter((key) => OPEN_API_METHODS.includes(key))
.reduce<WhookRawOperation<T>[]>((operations, method) => {
const operation = {
path,
method,
...API.paths[path]?.[method],
parameters: (API.paths[path]?.[method].parameters || []).concat(
API.paths[path]?.parameters || [],
),
};
return [...operations, operation];
}, operations),
[],
);
}