react-query-lightbase-codegen 1.0.2 → 1.0.5

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.
@@ -0,0 +1,489 @@
1
+ import lodash from 'lodash';
2
+ const { get, groupBy } = lodash;
3
+ import {
4
+ ComponentsObject,
5
+ OperationObject,
6
+ ParameterObject,
7
+ ReferenceObject,
8
+ ResponseObject,
9
+ SchemaObject,
10
+ } from 'openapi3-ts';
11
+ import { formatDescription, getResReqTypes, isReference, resolveValue } from './utils.js';
12
+ import pasCase from 'case';
13
+ import chalk from 'chalk';
14
+
15
+ const { pascal, camel } = pasCase;
16
+
17
+ const IdentifierRegexp = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
18
+
19
+ /**
20
+ * Return every params in a path
21
+ */
22
+ const getParamsInPath = (path: string) => {
23
+ let n;
24
+ const output = [];
25
+ const templatePathRegex = /\{(\w+)}/g;
26
+ while ((n = templatePathRegex.exec(path)) !== null) {
27
+ output.push(n[1]);
28
+ }
29
+
30
+ return output;
31
+ };
32
+
33
+ /**
34
+ * Generate a react-query component from openapi operation specs
35
+ */
36
+ export const createHook = ({
37
+ operation,
38
+ verb,
39
+ route,
40
+ operationIds,
41
+ parameters,
42
+ schemasComponents,
43
+ headerFilters,
44
+ overrides,
45
+ }: {
46
+ operation: OperationObject;
47
+ verb: string;
48
+ route: string;
49
+ operationIds: string[];
50
+ parameters: (ReferenceObject | ParameterObject)[] | undefined;
51
+ schemasComponents?: ComponentsObject;
52
+ headerFilters?: string[];
53
+ overrides?: Record<
54
+ string,
55
+ { type: 'query' } | { type: 'mutation' } | { type: 'infiniteQuery'; infiniteQueryParm: string }
56
+ >;
57
+ }) => {
58
+ const { operationId = route.replace('/', '') } = operation;
59
+ if (operationId === '*') {
60
+ throw new Error(`Invalid operationId/Route set for ${verb} ${route}`);
61
+ }
62
+ if (operationIds.includes(operationId)) {
63
+ return { implementation: '', imports: [], queryImports: [] };
64
+ }
65
+ operationIds.push(operationId);
66
+
67
+ route = route.replace(/\{/g, '${').replace('//', '/'); // `/pet/{id}` => `/pet/${id}`
68
+
69
+ // Remove the last param of the route if we are in the DELETE case
70
+ let lastParamInTheRoute: string | null = null;
71
+
72
+ const componentName = pascal(operationId!);
73
+
74
+ const isOk = ([statusCode]: [string, ResponseObject | ReferenceObject]) =>
75
+ statusCode.toString().startsWith('2');
76
+
77
+ const responseTypes = getResReqTypes(Object.entries(operation.responses).filter(isOk)) || 'void';
78
+ const requestBodyTypes = getResReqTypes([['body', operation.requestBody!]]);
79
+
80
+ let imports = [responseTypes];
81
+ let queryImports = [] as Array<'mutation' | 'query' | 'infiniteQuery'>;
82
+
83
+ const paramsInPath = getParamsInPath(route).filter(
84
+ (param) => !(verb === 'delete' && param === lastParamInTheRoute)
85
+ );
86
+
87
+ const {
88
+ query: queryParams = [],
89
+ path: pathParams = [],
90
+ header = [],
91
+ } = groupBy(
92
+ [...(parameters || []), ...(operation.parameters || [])].map<ParameterObject>((p) => {
93
+ if (isReference(p)) {
94
+ return get(schemasComponents, p.$ref.replace('#/components/', '').replace('/', '.'));
95
+ } else {
96
+ return p;
97
+ }
98
+ }),
99
+ 'in'
100
+ );
101
+
102
+ const headerParams = header.filter((p) => !headerFilters?.includes(p.name));
103
+
104
+ let enabled = [] as any;
105
+
106
+ // TODO: extract all requestBody or remove useQuery variants
107
+ let enabledParam = '!!params';
108
+ [...queryParams, ...pathParams, ...headerParams].forEach((item) => {
109
+ if (item.required) {
110
+ enabled.push(`["${item.name}"]`);
111
+ if (enabledParam && enabledParam !== '!!params') {
112
+ enabledParam += `&& params['${item.name}'] != null`;
113
+ } else {
114
+ enabledParam = `params['${item.name}'] != null`;
115
+ }
116
+ }
117
+ });
118
+
119
+ // `!props${enabled.join('== null && !props')}`;
120
+
121
+ const paramsTypes = paramsInPath
122
+ .map((p) => {
123
+ try {
124
+ const { name, required, schema } = pathParams.find((i) => i.name === p)!;
125
+ return `${name}${required ? '' : '?'}: ${resolveValue(schema!)}`;
126
+ } catch (err) {
127
+ throw new Error(`The path params ${p} can't be found in parameters (${operationId})`);
128
+ }
129
+ })
130
+ .join('; ');
131
+
132
+ const queryParamsType = queryParams
133
+ .map((p) => {
134
+ const processedName = IdentifierRegexp.test(p.name) ? p.name : `"${p.name}"`;
135
+ return `${formatDescription(p.description)}
136
+ ${processedName}${p.required ? '' : '?'}: ${resolveValue(p.schema!)}`;
137
+ })
138
+ .join(';\n ');
139
+
140
+ const headerType = headerParams
141
+ .map((p) => {
142
+ try {
143
+ const { name, required, schema } = headerParams.find((i) => i.name === p.name)!;
144
+ return `"${name}"${required ? '' : '?'}: ${resolveValue(schema!)}`;
145
+ } catch (err) {
146
+ throw new Error(`The path params ${p} can't be found in parameters (${operationId})`);
147
+ }
148
+ })
149
+ .join('; ');
150
+
151
+ // Retrieve the type of the param for delete verb
152
+ const lastParamInTheRouteDefinition =
153
+ operation.parameters && lastParamInTheRoute
154
+ ? (operation.parameters.find((p) => {
155
+ if (isReference(p)) {
156
+ return false;
157
+ }
158
+ return p.name === lastParamInTheRoute;
159
+ }) as ParameterObject | undefined) // Reference is not possible
160
+ : { schema: { type: 'string' } };
161
+
162
+ if (!lastParamInTheRouteDefinition) {
163
+ throw new Error(`The path params ${lastParamInTheRoute} can't be found in parameters (${operationId})`);
164
+ }
165
+
166
+ const defaultDescription = `type: ${verb}\noperationId: ${operationId}\nurl: ${route}`;
167
+
168
+ const description = formatDescription(
169
+ operation.summary && operation.description
170
+ ? `${defaultDescription}\n\n${operation.summary}\n\n${operation.description}`
171
+ : `${defaultDescription}`
172
+ );
173
+
174
+ let output = `\n\n${description}`;
175
+
176
+ const headerParam = headerType && headerType !== 'void' ? `${headerType};` : '';
177
+ const queryParam = queryParamsType && queryParamsType !== 'void' ? `${queryParamsType}` : '';
178
+ const requestBodyComponent = requestBodyTypes && requestBodyTypes !== 'void' ? `${requestBodyTypes}` : '';
179
+
180
+ if (requestBodyComponent) {
181
+ imports.push(requestBodyComponent);
182
+ }
183
+
184
+ const isUpdateRequest = ['post', 'patch', 'put'].includes(verb);
185
+
186
+ const fetchName = camel(componentName);
187
+
188
+ const createQueryHooks = (emptyParams?: boolean) => {
189
+ const params = emptyParams ? '' : `params: ${componentName}Params,`;
190
+ const key = emptyParams ? '' : `params`;
191
+ const mutationParams = emptyParams ? 'void' : `${componentName}Params`;
192
+ const queryParamType = emptyParams ? '' : `${componentName}Params &`;
193
+ const filterParams = emptyParams
194
+ ? '{ filters }: { filters?: QueryFilters }'
195
+ : `{ params, filters }: { params: ${componentName}Params, filters?: QueryFilters }`;
196
+ const cacheParams = emptyParams
197
+ ? `{updater, options}: {updater: Updater<${responseTypes} | undefined, ${responseTypes} | undefined>, options?: SetDataOptions | undefined}`
198
+ : `{params, updater, options}: {params: ${componentName}Params, updater: Updater<${responseTypes} | undefined, ${responseTypes} | undefined>, options?: SetDataOptions | undefined}`;
199
+ const queryKey = emptyParams
200
+ ? `use${componentName}Query.baseKey()`
201
+ : `[...use${componentName}Query.baseKey(), params]`;
202
+
203
+ const createQuery = () => `
204
+ type ${componentName}QueryProps<T = ${responseTypes}> = ${queryParamType} {
205
+ options?: UseQueryOptions<${responseTypes}, AxiosError, T, any>
206
+ }
207
+ export function use${componentName}Query<T = ${responseTypes}>({ options = {}, ...params }: ${componentName}QueryProps<T>) {
208
+ return useQuery(use${componentName}Query.queryKey(${key}), async () => ${fetchName}(${key}), { enabled: ${enabledParam}, ...options });
209
+ }
210
+
211
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
212
+
213
+ use${componentName}Query.queryKey = (${params}): QueryKey => ${queryKey};
214
+
215
+ use${componentName}Query.updateCache = (${cacheParams}) => queryClient.setQueryData<${responseTypes}>(use${componentName}Query.queryKey(${key}), updater, options);
216
+
217
+ use${componentName}Query.getQueryState = (${filterParams})=> queryClient.getQueryState<${responseTypes}>(use${componentName}Query.queryKey(${key}), filters);
218
+
219
+ use${componentName}Query.getQueryData = (${filterParams})=> queryClient.getQueryData<${responseTypes}>(use${componentName}Query.queryKey(${key}), filters);
220
+
221
+ use${componentName}Query.prefetch = (${params}) => queryClient.prefetchQuery<${responseTypes}>(use${componentName}Query.queryKey(${key}), ()=> ${fetchName}(${key}));
222
+
223
+ use${componentName}Query.cancelQueries = (${params}) => queryClient.cancelQueries(use${componentName}Query.queryKey(${key}))
224
+
225
+ use${componentName}Query.invalidate = (${params}) => queryClient.invalidateQueries<${responseTypes}>(use${componentName}Query.queryKey(${key}));
226
+
227
+ use${componentName}Query.refetchStale = (${params}) => queryClient.refetchQueries<${responseTypes}>(use${componentName}Query.queryKey(${key}), { stale: true });
228
+ `;
229
+
230
+ const getInfiniteQuery = ({ pageParam }: { pageParam: string }) => `
231
+ type ${componentName}QueryProps<T = ${responseTypes}> = ${queryParamType} {
232
+ options: UseInfiniteQueryOptions<${responseTypes}, AxiosError, T, any>
233
+ }
234
+ export function use${componentName}Query<T = ${responseTypes}>({ options = {}, ...params }: ${componentName}QueryProps<T>) {
235
+ return useInfiniteQuery(use${componentName}Query.queryKey(${key}), async ({ pageParam = 0 }) => ${fetchName}({${pageParam}: pageParam, ...params}), { enabled: ${enabledParam}, ...options });
236
+ }
237
+
238
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
239
+
240
+ use${componentName}Query.queryKey = (${params}): QueryKey => ${queryKey};
241
+
242
+ `;
243
+
244
+ const createMutation = () => `
245
+ type ${componentName}MutationProps<T> = {
246
+ options?: UseMutationOptions<${responseTypes}, AxiosError, ${mutationParams}, T>
247
+ }
248
+ export function use${componentName}Mutation<T = ${responseTypes}>(props?: ${componentName}MutationProps<T>) {
249
+ return useMutation(async (${key}) => ${fetchName}(${key}), props?.options)
250
+ };
251
+ `;
252
+
253
+ const override = overrides?.[operationId];
254
+ if (override?.type === 'query') {
255
+ console.log(chalk.blue(`⚙️ [${operationId}] has been changed to a useQuery hook`));
256
+ queryImports.push('query');
257
+ return createQuery();
258
+ }
259
+
260
+ if (override?.type === 'mutation') {
261
+ queryImports.push('mutation');
262
+ console.log(chalk.blue(`⚙️ [${operationId}] has been changed to a useMutation hook`));
263
+ return createMutation();
264
+ }
265
+
266
+ if (override?.type === 'infiniteQuery') {
267
+ console.log(chalk.blue(`⚙️ [${operationId}] has been changed to a useInfiniteQuery hook`));
268
+ queryImports.push('infiniteQuery');
269
+ return getInfiniteQuery({ pageParam: override.infiniteQueryParm });
270
+ }
271
+
272
+ if (verb === 'get') {
273
+ queryImports.push('query');
274
+ return createQuery();
275
+ }
276
+
277
+ queryImports.push('mutation');
278
+ return createMutation();
279
+ };
280
+
281
+ output += createQueryHooks(!requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam);
282
+
283
+ const hasRequestBodyArrray = requestBodyComponent && requestBodyComponent.includes('[]');
284
+ const body = hasRequestBodyArrray ? `{body: ${requestBodyComponent}}` : `${requestBodyComponent}`;
285
+ const bodyProps = hasRequestBodyArrray ? `{body, ...props}` : '{props}';
286
+
287
+ const generateProps = (props: ParameterObject[]) => {
288
+ return props.map((item) => `["${item.name}"]: props["${item.name}"]`).join(',');
289
+ };
290
+
291
+ const generateBodyProps = () => {
292
+ const definitionKey = Object.keys(schemasComponents?.schemas || {}).find(
293
+ (key) => pascal(key) === requestBodyComponent
294
+ );
295
+ if (definitionKey && !hasRequestBodyArrray) {
296
+ const scheme = schemasComponents?.schemas?.[definitionKey] as SchemaObject;
297
+ const generatedBodyProps = Object.keys(scheme.properties as SchemaObject)
298
+ .map((item: string) => `["${item}"]: props["${item}"]`)
299
+ .join(',');
300
+ return `const body = {${generatedBodyProps}}`;
301
+ }
302
+ return '';
303
+ };
304
+
305
+ if (!requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
306
+ output += `
307
+ const ${fetchName} = async () => {
308
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`);
309
+ return result.data;
310
+ }
311
+ `;
312
+ }
313
+
314
+ if (!requestBodyComponent && paramsInPath.length && queryParam && !headerParam) {
315
+ const config = isUpdateRequest ? 'body,{params}' : '{params}';
316
+ output += `
317
+ type ${componentName}Params = {
318
+ ${paramsTypes}
319
+ ${queryParamsType};
320
+ }
321
+
322
+ const ${fetchName} = async (props:${componentName}Params) => {
323
+ const {${paramsInPath.join(', ')}, ...params} = props
324
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config})
325
+ return result.data;
326
+ }`;
327
+ }
328
+
329
+ if (!requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
330
+ output += `
331
+ type ${componentName}Params = {
332
+ ${paramsTypes}
333
+ }
334
+
335
+ const ${fetchName} = async (props: ${componentName}Params ) => {
336
+ const result = await api.${verb}<${responseTypes}>(\`${route.replace(/\{/g, '{props.')}\`);
337
+ return result.data;
338
+ }
339
+ `;
340
+ }
341
+
342
+ if (!requestBodyComponent && !paramsInPath.length && queryParam && !headerParam) {
343
+ const config = isUpdateRequest ? 'null,{params}' : '{params}';
344
+ output += `
345
+ type ${componentName}Params = {
346
+ ${queryParamsType}
347
+ }
348
+
349
+ const ${fetchName} = async (params: ${componentName}Params) => {
350
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config})
351
+ return result.data;
352
+ }
353
+ `;
354
+ }
355
+ if (!requestBodyComponent && !paramsInPath.length && queryParam && headerParam) {
356
+ const config = isUpdateRequest ? 'null,{headers, params: queryParams}' : '{headers, params: queryParams}';
357
+ output += `
358
+ type ${componentName}Params = {
359
+ ${headerParam}
360
+ ${queryParamsType}
361
+ }
362
+ const ${fetchName} = async (props: ${componentName}Params) => {
363
+ const headers = {${generateProps(header)}}
364
+ const queryParams = {${generateProps(queryParams)}}
365
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config})
366
+ return result.data
367
+ }`;
368
+ }
369
+ if (!requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
370
+ const config = isUpdateRequest ? 'null,{headers}' : '{headers}';
371
+ output += `
372
+ type ${componentName}Params = {
373
+ ${headerParam}
374
+ };
375
+
376
+ const ${fetchName} = async (headers: ${componentName}Params) => {
377
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config});
378
+ return result.data;
379
+ }
380
+ `;
381
+ }
382
+
383
+ if (requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
384
+ output += `
385
+ type ${componentName}Params = ${requestBodyComponent}
386
+
387
+ const ${fetchName} = async (body: ${componentName}Params) => {
388
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, body)
389
+ return result.data
390
+ }
391
+ `;
392
+ }
393
+
394
+ if (requestBodyComponent && !paramsInPath.length && queryParam && !headerParam) {
395
+ output += `
396
+ type ${componentName}Params = ${body} & {
397
+ ${queryParamsType}
398
+ }
399
+
400
+ const ${fetchName} = async (${bodyProps}: ${componentName}Params) => {
401
+ ${generateBodyProps()}
402
+ const params = {${generateProps(queryParams)}}
403
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, body, {params})
404
+ return result.data
405
+ }
406
+ `;
407
+ }
408
+
409
+ if (requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
410
+ output += `
411
+ type ${componentName}Params = ${body} & {
412
+ ${headerParam}
413
+ };
414
+
415
+ const ${fetchName} = async (${bodyProps}: ${componentName}Params) => {
416
+ ${generateBodyProps()}
417
+ const headers = {${generateProps(header)}}
418
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, body, {headers})
419
+ return result.data
420
+ }
421
+ `;
422
+ }
423
+
424
+ if (requestBodyComponent && !paramsInPath.length && queryParam && headerParam) {
425
+ output += `
426
+ type ${componentName}Params = ${body} & {
427
+ ${headerParam}
428
+ ${paramsTypes}
429
+ };
430
+
431
+ const ${fetchName} = async (${bodyProps}: ${componentName}Params) => {
432
+ ${generateBodyProps()}
433
+ const headers = {${generateProps(header)}}
434
+ const params = {${generateProps(queryParams)}}
435
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, body, {headers, params})
436
+ return result.data
437
+ }
438
+ `;
439
+ }
440
+
441
+ if (requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
442
+ output += `
443
+ type ${componentName}Params = ${body} & {
444
+ ${headerParam}
445
+ ${paramsTypes}
446
+ };
447
+
448
+ const ${fetchName} = async (${bodyProps}: ${componentName}Params) => {
449
+ ${generateBodyProps()}
450
+ const result = await api.${verb}<${responseTypes}>(\`${route.replace(/\{/g, '{props.')}\`, body)
451
+ return result.data
452
+ }
453
+ `;
454
+ }
455
+
456
+ if (requestBodyComponent && paramsInPath.length && queryParam && !headerParam) {
457
+ output += `// TODO: NOT SUPPORTED requestBodyComponent && paramsInPath && queryParam)`;
458
+ }
459
+
460
+ if (requestBodyComponent && paramsInPath.length && queryParam && headerParam) {
461
+ output += `// TODO: NOT SUPPORTED requestBodyComponent && paramsInPath && queryParam && headerParam)`;
462
+ }
463
+
464
+ if (!requestBodyComponent && paramsInPath.length && !queryParam && headerParam) {
465
+ const config = isUpdateRequest ? 'null,{headers}' : '{headers}';
466
+ output += `
467
+ type ${componentName}Params = {
468
+ ${headerParam}
469
+ ${paramsTypes}
470
+ };
471
+
472
+ const ${fetchName} = async (props: ${componentName}Params) => {
473
+ const headers = {${generateProps(header)}}
474
+ const result = await api.${verb}<${responseTypes}>(\`${route.replace(/\{/g, '{props.')}\`, ${config})
475
+ return result.data
476
+ }
477
+ `;
478
+ }
479
+
480
+ if (!requestBodyComponent && paramsInPath.length && queryParam && headerParam) {
481
+ output += `// TODO: NOT SUPPORTED (paramsInPath && queryParam && headerParam)`;
482
+ }
483
+
484
+ if (requestBodyComponent && paramsInPath.length && !queryParam && headerParam) {
485
+ output += `// TODO: NOT SUPPORTED (requestBodyComponent && paramsInPath && headerParam)`;
486
+ }
487
+
488
+ return { implementation: output, imports, queryImports };
489
+ };
@@ -0,0 +1,41 @@
1
+ export const generateImports = ({
2
+ schemaName,
3
+ apiDirectory,
4
+ queryClientDir,
5
+ schemaImports,
6
+ queryImports,
7
+ }: {
8
+ apiDirectory: string;
9
+ queryClientDir: string;
10
+ schemaName: string;
11
+ schemaImports: string[];
12
+ queryImports: ('query' | 'mutation' | 'infiniteQuery')[];
13
+ }) => {
14
+ const importTypes = schemaImports.join(',');
15
+ let imports = [] as string[];
16
+ if (queryImports.includes('query')) {
17
+ imports = [...imports, 'useQuery', 'UseQueryOptions', 'QueryKey', 'SetDataOptions', 'QueryFilters'];
18
+ }
19
+ if (queryImports.includes('infiniteQuery')) {
20
+ imports = [...imports, 'useInfiniteQuery', 'UseInfiniteQueryOptions', 'QueryKey'];
21
+ }
22
+ if (queryImports.includes('mutation')) {
23
+ imports = [...imports, 'UseMutationOptions', 'useMutation'];
24
+ }
25
+
26
+ const importString = [...new Set(imports)].join(',');
27
+
28
+ return `
29
+ import {
30
+ ${importString}
31
+ } from '@tanstack/react-query';
32
+
33
+ import { AxiosError } from 'axios';
34
+ import { api } from '${apiDirectory}';
35
+ import { queryClient } from '${queryClientDir}';
36
+
37
+ import {${importTypes}} from './${schemaName}'
38
+
39
+ type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput);
40
+ `;
41
+ };
@@ -0,0 +1,114 @@
1
+ import pasCase from 'case';
2
+ import lodash from 'lodash';
3
+ const { isEmpty } = lodash;
4
+ const { pascal } = pasCase;
5
+ import { ComponentsObject, OpenAPIObject, SchemaObject } from 'openapi3-ts';
6
+ import { formatDescription, getScalar, isReference, resolveValue } from './utils.js';
7
+
8
+ import { getDocs, getResReqTypes } from './utils.js';
9
+
10
+ /**
11
+ * Generate the interface string
12
+ */
13
+ const generateInterface = (name: string, schema: SchemaObject) => {
14
+ const scalar = getScalar(schema);
15
+ return `${formatDescription(schema.description)}
16
+ export type ${pascal(name)} = ${scalar}
17
+ `;
18
+ };
19
+
20
+ /**
21
+ * Extract all types from #/components/schemas
22
+ */
23
+ const generateSchemasDefinition = (schemas: ComponentsObject['schemas'] = {}) => {
24
+ if (isEmpty(schemas)) {
25
+ return '';
26
+ }
27
+
28
+ return (
29
+ '\n // SCEHMAS \n' +
30
+ Object.entries(schemas)
31
+ .map(([name, schema]) =>
32
+ !isReference(schema) &&
33
+ (!schema.type || schema.type === 'object') &&
34
+ !schema.allOf &&
35
+ !schema.oneOf &&
36
+ !isReference(schema) &&
37
+ !schema.nullable
38
+ ? generateInterface(name, schema)
39
+ : `${formatDescription(isReference(schema) ? undefined : schema.description)} export type ${pascal(
40
+ name
41
+ )} = ${resolveValue(schema)};`
42
+ )
43
+ .join('\n\n') +
44
+ '\n'
45
+ );
46
+ };
47
+
48
+ /**
49
+ * Extract all types from #/components/requestBodies
50
+ */
51
+ const generateRequestBodiesDefinition = (requestBodies: ComponentsObject['requestBodies'] = {}) => {
52
+ if (isEmpty(requestBodies)) {
53
+ return '';
54
+ }
55
+
56
+ return (
57
+ '\n // REQUEST BODIES \n' +
58
+ Object.entries(requestBodies)
59
+ .map(([name, requestBody]) => {
60
+ const doc = getDocs(requestBody);
61
+ const type = getResReqTypes([['', requestBody]]);
62
+ const isEmptyInterface = type === '{}';
63
+ if (isEmptyInterface) {
64
+ return `${doc}\nexport type ${pascal(name)}RequestBody = ${type}`;
65
+ } else if (type.includes('{') && !type.includes('|') && !type.includes('&')) {
66
+ return `${doc}\nexport type ${pascal(name)}RequestBody = ${type}`;
67
+ } else {
68
+ return `${doc}\nexport type ${pascal(name)}RequestBody = ${type};`;
69
+ }
70
+ })
71
+ .join('\n\n') +
72
+ '\n'
73
+ );
74
+ };
75
+
76
+ /**
77
+ * Extract all types from #/components/responses
78
+ */
79
+ const generateResponsesDefinition = (responses: ComponentsObject['responses'] = {}) => {
80
+ if (isEmpty(responses)) {
81
+ return '';
82
+ }
83
+
84
+ return (
85
+ '\n // RESPONSES \n' +
86
+ Object.entries(responses)
87
+ .map(([name, response]) => {
88
+ const doc = getDocs(response);
89
+ const type = getResReqTypes([['', response]]);
90
+ const isEmptyInterface = type === '{}';
91
+ if (isEmptyInterface) {
92
+ return `export type RQ${pascal(name)}Response = ${type}`;
93
+ } else if (type.includes('{') && !type.includes('|') && !type.includes('&')) {
94
+ return `${doc}export type RQ${pascal(name)}Response = ${type}`;
95
+ } else {
96
+ return `${doc}export type RQ${pascal(name)}Response = ${type};`;
97
+ }
98
+ })
99
+ .join('\n\n') +
100
+ '\n'
101
+ );
102
+ };
103
+
104
+ /**
105
+ * Extract all types from #/components/schemas
106
+ */
107
+ export const generateSchemas = ({ spec }: { spec: OpenAPIObject }) => {
108
+ const schemaOutput =
109
+ generateRequestBodiesDefinition(spec.components?.requestBodies) +
110
+ generateResponsesDefinition(spec.components?.responses) +
111
+ generateSchemasDefinition(spec.components?.schemas);
112
+
113
+ return schemaOutput;
114
+ };