react-query-lightbase-codegen 0.2.0 → 0.5.0

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