react-query-lightbase-codegen 1.0.0 → 1.0.1

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.
Files changed (47) hide show
  1. package/lib/commonjs/convertSwaggerFile.js +37 -0
  2. package/lib/commonjs/convertSwaggerFile.js.map +1 -0
  3. package/lib/commonjs/generateHooks.js +492 -0
  4. package/lib/commonjs/generateHooks.js.map +1 -0
  5. package/lib/commonjs/generateImports.js +48 -0
  6. package/lib/commonjs/generateImports.js.map +1 -0
  7. package/lib/commonjs/generateSchemas.js +119 -0
  8. package/lib/commonjs/generateSchemas.js.map +1 -0
  9. package/lib/commonjs/importSpecs.js +117 -0
  10. package/lib/commonjs/importSpecs.js.map +1 -0
  11. package/lib/commonjs/index.js +22 -0
  12. package/lib/commonjs/index.js.map +1 -0
  13. package/lib/commonjs/utils.js +212 -0
  14. package/lib/commonjs/utils.js.map +1 -0
  15. package/lib/{cjs → src}/convertSwaggerFile.js +7 -10
  16. package/lib/src/generateHooks.js +249 -0
  17. package/lib/src/generateImports.js +29 -0
  18. package/lib/src/generateSchemas.js +108 -0
  19. package/lib/src/importSpecs.js +134 -0
  20. package/lib/src/index.js +7 -0
  21. package/lib/{cjs → src}/utils.js +40 -36
  22. package/lib/typescript/convertSwaggerFile.d.ts +5 -0
  23. package/lib/typescript/generateHooks.d.ts +25 -0
  24. package/lib/typescript/generateImports.d.ts +7 -0
  25. package/lib/typescript/generateSchemas.d.ts +7 -0
  26. package/lib/typescript/importSpecs.d.ts +15 -0
  27. package/lib/{esm/index.js → typescript/index.d.ts} +0 -0
  28. package/lib/typescript/utils.d.ts +24 -0
  29. package/package.json +26 -6
  30. package/src/convertSwaggerFile.ts +25 -0
  31. package/src/generateHooks.ts +490 -0
  32. package/src/generateImports.ts +41 -0
  33. package/src/generateSchemas.ts +114 -0
  34. package/src/importSpecs.ts +110 -0
  35. package/src/index.ts +3 -0
  36. package/src/utils.ts +190 -0
  37. package/lib/cjs/generateHooks.js +0 -401
  38. package/lib/cjs/generateImports.js +0 -31
  39. package/lib/cjs/generateSchemas.js +0 -103
  40. package/lib/cjs/importSpecs.js +0 -87
  41. package/lib/cjs/index.js +0 -7
  42. package/lib/esm/convertSwaggerFile.js +0 -25
  43. package/lib/esm/generateHooks.js +0 -394
  44. package/lib/esm/generateImports.js +0 -27
  45. package/lib/esm/generateSchemas.js +0 -96
  46. package/lib/esm/importSpecs.js +0 -80
  47. package/lib/esm/utils.js +0 -156
@@ -1,394 +0,0 @@
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
- };
@@ -1,27 +0,0 @@
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
- };
@@ -1,96 +0,0 @@
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
- };
@@ -1,80 +0,0 @@
1
- import chalk from 'chalk';
2
- import { readFileSync, writeFileSync, readdir, mkdirSync } from 'fs';
3
- import { join, parse } from 'path';
4
- import { convertSwaggerFile } from './convertSwaggerFile.js';
5
- import { createHook } from './generateHooks.js';
6
- import { generateImports } from './generateImports.js';
7
- import { generateSchemas } from './generateSchemas.js';
8
- export function importSpecs({ sourceDirectory, exportDirectory, apiDirectory, queryClientDir, headerFilters, overrides, }) {
9
- readdir(sourceDirectory, function (err, filenames) {
10
- if (err) {
11
- console.log(err);
12
- throw err;
13
- }
14
- filenames.map(async (filename) => {
15
- try {
16
- const data = readFileSync(join(process.cwd(), sourceDirectory + '/' + filename), 'utf-8');
17
- const { ext } = parse(sourceDirectory + '/' + filename);
18
- const format = ['.yaml', '.yml'].includes(ext.toLowerCase()) ? 'yaml' : 'json';
19
- let spec = await convertSwaggerFile(data, format);
20
- const schemaName = `useQueries${filename.split('.')[0]}.schema`;
21
- const hooksName = `useQueries${filename.split('.')[0]}`;
22
- const name = filename.split('.')[0];
23
- mkdirSync(join(process.cwd(), `${exportDirectory}/${name}`), { recursive: true });
24
- const operationIds = [];
25
- let hooks = '';
26
- let schemaImportsArray = [];
27
- let collectedQueryImports = [];
28
- Object.entries(spec.paths).forEach(([route, verbs]) => {
29
- Object.entries(verbs).forEach(([verb, operation]) => {
30
- if (['get', 'post', 'patch', 'put', 'delete'].includes(verb) && !operation.deprecated) {
31
- const { implementation, imports, queryImports } = createHook({
32
- operation,
33
- verb,
34
- route: (spec.basePath || '') + route,
35
- operationIds,
36
- parameters: verbs.parameters,
37
- schemasComponents: spec.components,
38
- headerFilters,
39
- overrides,
40
- });
41
- hooks += implementation;
42
- imports.forEach((element) => {
43
- const formattedImport = element.replace('[]', '');
44
- if (!schemaImportsArray.includes(formattedImport) &&
45
- element !== 'void' &&
46
- element !== 'string' &&
47
- !element.includes('{')) {
48
- schemaImportsArray.push(formattedImport);
49
- }
50
- });
51
- queryImports.forEach((element) => {
52
- if (!schemaImportsArray.includes(element)) {
53
- collectedQueryImports.push(element);
54
- }
55
- });
56
- }
57
- });
58
- });
59
- const imports = generateImports({
60
- apiDirectory,
61
- queryClientDir,
62
- schemaName,
63
- schemaImports: schemaImportsArray,
64
- queryImports: collectedQueryImports,
65
- });
66
- writeFileSync(join(process.cwd(), `${exportDirectory}/${name}/${hooksName}.tsx`), imports + hooks);
67
- const schemas = generateSchemas({ spec });
68
- writeFileSync(join(process.cwd(), `${exportDirectory}/${name}/${schemaName}.tsx`), schemas);
69
- console.log(chalk.green(`🎉 [${filename}] Your OpenAPI spec has been converted into react query hooks`));
70
- }
71
- catch (error) {
72
- if (error.code === 'EISDIR') {
73
- console.log(chalk.red('nested folder structure not supported'));
74
- return;
75
- }
76
- console.log(chalk.red(`[${filename}]:`), chalk.red(error));
77
- }
78
- });
79
- });
80
- }