react-query-lightbase-codegen 1.0.2 → 1.0.3

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.
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "react-query-lightbase-codegen",
3
3
  "description": "Fully typed react query code generation tool based on openApi specifications",
4
- "version": "1.0.2",
4
+ "version": "1.0.3",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "exports": "./dist/index.js",
8
8
  "files": [
9
- "lib/"
9
+ "src",
10
+ "dist"
10
11
  ],
11
12
  "keywords": [
12
13
  "rest",
@@ -0,0 +1,25 @@
1
+ import { OpenAPIObject } from 'openapi3-ts';
2
+ import swagger2openapi from 'swagger2openapi';
3
+ import yaml from 'js-yaml';
4
+
5
+ /**
6
+ * Import and parse the openapi spec from a yaml/json
7
+ */
8
+ export const convertSwaggerFile = (data: string, extension: 'yaml' | 'json'): Promise<OpenAPIObject> => {
9
+ const schema = extension === 'yaml' ? yaml.load(data) : JSON.parse(data);
10
+ return new Promise((resolve, reject) => {
11
+ if (!schema.openapi || !schema.openapi.startsWith('3.')) {
12
+ swagger2openapi.convertObj(schema, {}, (err, convertedObj) => {
13
+ if (err) {
14
+ reject(err);
15
+ } else {
16
+ // @ts-ignore
17
+ convertedObj.openapi.basePath = convertedObj.original.basePath;
18
+ resolve(convertedObj.openapi);
19
+ }
20
+ });
21
+ } else {
22
+ resolve(schema);
23
+ }
24
+ });
25
+ };
@@ -0,0 +1,490 @@
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 generateProps = (props: ParameterObject[]) => {
187
+ return props.map((item) => `["${item.name}"]: props["${item.name}"]`).join(',');
188
+ };
189
+
190
+ const generateBodyProps = () => {
191
+ const definitionKey = Object.keys(schemasComponents?.schemas || {}).find(
192
+ (key) => pascal(key) === requestBodyComponent
193
+ );
194
+ if (definitionKey) {
195
+ const scheme = schemasComponents?.schemas?.[definitionKey] as SchemaObject;
196
+ return Object.keys(scheme.properties as SchemaObject)
197
+ .map((item: string) => `["${item}"]: props["${item}"]`)
198
+ .join(',');
199
+ }
200
+ };
201
+
202
+ const fetchName = camel(componentName);
203
+
204
+ const createQueryHooks = (emptyParams?: boolean) => {
205
+ const params = emptyParams ? '' : `params: ${componentName}Params,`;
206
+ const key = emptyParams ? '' : `params`;
207
+ const mutationParams = emptyParams ? 'void' : `${componentName}Params`;
208
+ const queryParamType = emptyParams ? '' : `${componentName}Params &`;
209
+ const filterParams = emptyParams
210
+ ? '{ filters }: { filters?: QueryFilters }'
211
+ : `{ params, filters }: { params: ${componentName}Params, filters?: QueryFilters }`;
212
+ const cacheParams = emptyParams
213
+ ? `{updater, options}: {updater: Updater<${responseTypes} | undefined, ${responseTypes} | undefined>, options?: SetDataOptions | undefined}`
214
+ : `{params, updater, options}: {params: ${componentName}Params, updater: Updater<${responseTypes} | undefined, ${responseTypes} | undefined>, options?: SetDataOptions | undefined}`;
215
+ const queryKey = emptyParams
216
+ ? `use${componentName}Query.baseKey()`
217
+ : `[...use${componentName}Query.baseKey(), params]`;
218
+
219
+ const createQuery = () => `
220
+ type ${componentName}QueryProps<T = ${responseTypes}> = ${queryParamType} {
221
+ options?: UseQueryOptions<${responseTypes}, AxiosError, T, any>
222
+ }
223
+ export function use${componentName}Query<T = ${responseTypes}>({ options = {}, ...params }: ${componentName}QueryProps<T>) {
224
+ return useQuery(use${componentName}Query.queryKey(${key}), async () => ${fetchName}(${key}), { enabled: ${enabledParam}, ...options });
225
+ }
226
+
227
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
228
+
229
+ use${componentName}Query.queryKey = (${params}): QueryKey => ${queryKey};
230
+
231
+ use${componentName}Query.updateCache = (${cacheParams}) => queryClient.setQueryData<${responseTypes}>(use${componentName}Query.queryKey(${key}), updater, options);
232
+
233
+ use${componentName}Query.getQueryState = (${filterParams})=> queryClient.getQueryState<${responseTypes}>(use${componentName}Query.queryKey(${key}), filters);
234
+
235
+ use${componentName}Query.getQueryData = (${filterParams})=> queryClient.getQueryData<${responseTypes}>(use${componentName}Query.queryKey(${key}), filters);
236
+
237
+ use${componentName}Query.prefetch = (${params}) => queryClient.prefetchQuery<${responseTypes}>(use${componentName}Query.queryKey(${key}), ()=> ${fetchName}(${key}));
238
+
239
+ use${componentName}Query.cancelQueries = (${params}) => queryClient.cancelQueries(use${componentName}Query.queryKey(${key}))
240
+
241
+ use${componentName}Query.invalidate = (${params}) => queryClient.invalidateQueries<${responseTypes}>(use${componentName}Query.queryKey(${key}));
242
+
243
+ use${componentName}Query.refetchStale = (${params}) => queryClient.refetchQueries<${responseTypes}>(use${componentName}Query.queryKey(${key}), { stale: true });
244
+ `;
245
+
246
+ const getInfiniteQuery = ({ pageParam }: { pageParam: string }) => `
247
+ type ${componentName}QueryProps<T = ${responseTypes}> = ${queryParamType} {
248
+ options: UseInfiniteQueryOptions<${responseTypes}, AxiosError, T, any>
249
+ }
250
+ export function use${componentName}Query<T = ${responseTypes}>({ options = {}, ...params }: ${componentName}QueryProps<T>) {
251
+ return useInfiniteQuery(use${componentName}Query.queryKey(${key}), async ({ pageParam = 0 }) => ${fetchName}({${pageParam}: pageParam, ...params}), { enabled: ${enabledParam}, ...options });
252
+ }
253
+
254
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
255
+
256
+ use${componentName}Query.queryKey = (${params}): QueryKey => ${queryKey};
257
+
258
+ `;
259
+
260
+ const createMutation = () => `
261
+ type ${componentName}MutationProps<T> = {
262
+ options?: UseMutationOptions<${responseTypes}, AxiosError, ${mutationParams}, T>
263
+ }
264
+ export function use${componentName}Mutation<T = ${responseTypes}>(props?: ${componentName}MutationProps<T>) {
265
+ return useMutation(async (${key}) => ${fetchName}(${key}), props?.options)
266
+ };
267
+ `;
268
+
269
+ const override = overrides?.[operationId];
270
+ if (override?.type === 'query') {
271
+ console.log(chalk.blue(`⚙️ [${operationId}] has been changed to a useQuery hook`));
272
+ queryImports.push('query');
273
+ return createQuery();
274
+ }
275
+
276
+ if (override?.type === 'mutation') {
277
+ queryImports.push('mutation');
278
+ console.log(chalk.blue(`⚙️ [${operationId}] has been changed to a useMutation hook`));
279
+ return createMutation();
280
+ }
281
+
282
+ if (override?.type === 'infiniteQuery') {
283
+ console.log(chalk.blue(`⚙️ [${operationId}] has been changed to a useInfiniteQuery hook`));
284
+ queryImports.push('infiniteQuery');
285
+ return getInfiniteQuery({ pageParam: override.infiniteQueryParm });
286
+ }
287
+
288
+ if (verb === 'get') {
289
+ queryImports.push('query');
290
+ return createQuery();
291
+ }
292
+
293
+ queryImports.push('mutation');
294
+ return createMutation();
295
+ };
296
+
297
+ output += createQueryHooks(!requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam);
298
+
299
+ if (!requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
300
+ output += `
301
+ const ${fetchName} = async () => {
302
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`);
303
+ return result.data;
304
+ }
305
+ `;
306
+ }
307
+
308
+ if (!requestBodyComponent && paramsInPath.length && queryParam && !headerParam) {
309
+ const config = isUpdateRequest ? 'body,{params}' : '{params}';
310
+ output += `
311
+ type ${componentName}Params = {
312
+ ${paramsTypes}
313
+ ${queryParamsType};
314
+ }
315
+
316
+ const ${fetchName} = async (props:${componentName}Params) => {
317
+ const {${paramsInPath.join(', ')}, ...params} = props
318
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config})
319
+ return result.data;
320
+ }`;
321
+ }
322
+
323
+ if (!requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
324
+ output += `
325
+ type ${componentName}Params = {
326
+ ${paramsTypes}
327
+ }
328
+
329
+ const ${fetchName} = async (props: ${componentName}Params ) => {
330
+ const result = await api.${verb}<${responseTypes}>(\`${route.replace(/\{/g, '{props.')}\`);
331
+ return result.data;
332
+ }
333
+ `;
334
+ }
335
+
336
+ if (!requestBodyComponent && !paramsInPath.length && queryParam && !headerParam) {
337
+ const config = isUpdateRequest ? 'null,{params}' : '{params}';
338
+ output += `
339
+ type ${componentName}Params = {
340
+ ${queryParamsType}
341
+ }
342
+
343
+ const ${fetchName} = async (params: ${componentName}Params) => {
344
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config})
345
+ return result.data;
346
+ }
347
+ `;
348
+ }
349
+ if (!requestBodyComponent && !paramsInPath.length && queryParam && headerParam) {
350
+ const config = isUpdateRequest ? 'null,{headers, params: queryParams}' : '{headers, params: queryParams}';
351
+ output += `
352
+ type ${componentName}Params = {
353
+ ${headerParam}
354
+ ${queryParamsType}
355
+ }
356
+ const ${fetchName} = async (props: ${componentName}Params) => {
357
+ const headers = {${generateProps(header)}}
358
+ const queryParams = {${generateProps(queryParams)}}
359
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config})
360
+ return result.data
361
+ }`;
362
+ }
363
+ if (!requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
364
+ const config = isUpdateRequest ? 'null,{headers}' : '{headers}';
365
+ output += `
366
+ type ${componentName}Params = {
367
+ ${headerParam}
368
+ };
369
+
370
+ const ${fetchName} = async (headers: ${componentName}Params) => {
371
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config});
372
+ return result.data;
373
+ }
374
+ `;
375
+ }
376
+
377
+ if (requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
378
+ output += `
379
+ type ${componentName}Params = ${requestBodyComponent}
380
+
381
+ const ${fetchName} = async (body: ${componentName}Params) => {
382
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, body)
383
+ return result.data
384
+ }
385
+ `;
386
+ }
387
+
388
+ if (requestBodyComponent && !paramsInPath.length && queryParam && !headerParam) {
389
+ const config = isUpdateRequest ? 'null,{headers, params: queryParams}' : '{headers, params: queryParams}';
390
+ const queryParamsProps = queryParams.map((item) => `["${item.name}"]: props["${item.name}"]`);
391
+ output += `
392
+ type ${componentName}Params = ${requestBodyComponent} & {
393
+ ${queryParamsType}
394
+ }
395
+
396
+ type ${componentName}QueryProps<T = ${responseTypes}> = ${componentName}Params & {
397
+ const body = {${generateBodyProps()}}
398
+ const params = {${generateProps(queryParams)}}
399
+ options?: UseQueryOptions<${responseTypes}, AxiosError, T, any>
400
+ }
401
+
402
+ const ${fetchName} = async ({body, params}: ${componentName}Params) => {
403
+ const queryParams = {${queryParamsProps.join(',')}}
404
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config})
405
+ return result.data
406
+ }
407
+ `;
408
+ }
409
+
410
+ if (requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
411
+ output += `
412
+ type ${componentName}Params = ${requestBodyComponent} & {
413
+ ${headerParam}
414
+ };
415
+
416
+ const ${fetchName} = async (props: ${componentName}Params) => {
417
+ const headers = {${generateProps(header)}}
418
+ const body = {${generateBodyProps()}}
419
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, body, {headers})
420
+ return result.data
421
+ }
422
+ `;
423
+ }
424
+
425
+ if (requestBodyComponent && !paramsInPath.length && queryParam && headerParam) {
426
+ output += `
427
+ type ${componentName}Params = ${requestBodyComponent} & {
428
+ ${headerParam}
429
+ ${paramsTypes}
430
+ };
431
+
432
+ const ${fetchName} = async (props: ${componentName}Params) => {
433
+ const body = {${generateBodyProps()}}
434
+ const headers = {${generateProps(header)}}
435
+ const params = {${generateProps(queryParams)}}
436
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, body, {headers, params})
437
+ return result.data
438
+ }
439
+ `;
440
+ }
441
+
442
+ if (requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
443
+ output += `
444
+ type ${componentName}Params = ${requestBodyComponent} & {
445
+ ${headerParam}
446
+ ${paramsTypes}
447
+ };
448
+
449
+ const ${fetchName} = async (props: ${componentName}Params) => {
450
+ const body = {${generateBodyProps()}}
451
+ const result = await api.${verb}<${responseTypes}>(\`${route.replace(/\{/g, '{props.')}\`, body)
452
+ return result.data
453
+ }
454
+ `;
455
+ }
456
+
457
+ if (requestBodyComponent && paramsInPath.length && queryParam && !headerParam) {
458
+ output += `// TODO: NOT SUPPORTED requestBodyComponent && paramsInPath && queryParam)`;
459
+ }
460
+
461
+ if (requestBodyComponent && paramsInPath.length && queryParam && headerParam) {
462
+ output += `// TODO: NOT SUPPORTED requestBodyComponent && paramsInPath && queryParam && headerParam)`;
463
+ }
464
+
465
+ if (!requestBodyComponent && paramsInPath.length && !queryParam && headerParam) {
466
+ const config = isUpdateRequest ? 'null,{headers}' : '{headers}';
467
+ output += `
468
+ type ${componentName}Params = {
469
+ ${headerParam}
470
+ ${paramsTypes}
471
+ };
472
+
473
+ const ${fetchName} = async (props: ${componentName}Params) => {
474
+ const headers = {${generateProps(header)}}
475
+ const result = await api.${verb}<${responseTypes}>(\`${route.replace(/\{/g, '{props.')}\`, ${config})
476
+ return result.data
477
+ }
478
+ `;
479
+ }
480
+
481
+ if (!requestBodyComponent && paramsInPath.length && queryParam && headerParam) {
482
+ output += `// TODO: NOT SUPPORTED (paramsInPath && queryParam && headerParam)`;
483
+ }
484
+
485
+ if (requestBodyComponent && paramsInPath.length && !queryParam && headerParam) {
486
+ output += `// TODO: NOT SUPPORTED (requestBodyComponent && paramsInPath && headerParam)`;
487
+ }
488
+
489
+ return { implementation: output, imports, queryImports };
490
+ };
@@ -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
+ };
@@ -0,0 +1,110 @@
1
+ import chalk from 'chalk';
2
+ import { readFileSync, writeFileSync, readdir, mkdirSync } from 'fs';
3
+ import { OperationObject, PathItemObject } from 'openapi3-ts';
4
+ import { join, parse } from 'path';
5
+ import { convertSwaggerFile } from './convertSwaggerFile.js';
6
+ import { createHook } from './generateHooks.js';
7
+ import { generateImports } from './generateImports.js';
8
+ import { generateSchemas } from './generateSchemas.js';
9
+
10
+ export function importSpecs({
11
+ sourceDirectory,
12
+ exportDirectory,
13
+ apiDirectory,
14
+ queryClientDir,
15
+ headerFilters,
16
+ overrides,
17
+ }: {
18
+ sourceDirectory: string;
19
+ exportDirectory: string;
20
+ apiDirectory: string;
21
+ queryClientDir: string;
22
+ headerFilters?: string[];
23
+ overrides?: Record<
24
+ string,
25
+ { type: 'query' } | { type: 'mutation' } | { type: 'infiniteQuery'; infiniteQueryParm: string }
26
+ >;
27
+ }) {
28
+ readdir(sourceDirectory, function (err, filenames) {
29
+ if (err) {
30
+ console.log(err);
31
+ throw err;
32
+ }
33
+ filenames.map(async (filename) => {
34
+ try {
35
+ const data = readFileSync(join(process.cwd(), sourceDirectory + '/' + filename), 'utf-8');
36
+ const { ext } = parse(sourceDirectory + '/' + filename);
37
+ const format = ['.yaml', '.yml'].includes(ext.toLowerCase()) ? 'yaml' : 'json';
38
+ let spec = await convertSwaggerFile(data, format);
39
+
40
+ const schemaName = `useQueries${filename.split('.')[0]}.schema`;
41
+ const hooksName = `useQueries${filename.split('.')[0]}`;
42
+ const name = filename.split('.')[0];
43
+ mkdirSync(join(process.cwd(), `${exportDirectory}/${name}`), { recursive: true });
44
+
45
+ const operationIds: string[] = [];
46
+
47
+ let hooks = '';
48
+ let schemaImportsArray = [] as string[];
49
+ let collectedQueryImports = [] as ('query' | 'mutation' | 'infiniteQuery')[];
50
+ Object.entries(spec.paths).forEach(([route, verbs]: [string, PathItemObject]) => {
51
+ Object.entries(verbs).forEach(([verb, operation]: [string, OperationObject]) => {
52
+ if (['get', 'post', 'patch', 'put', 'delete'].includes(verb) && !operation.deprecated) {
53
+ const { implementation, imports, queryImports } = createHook({
54
+ operation,
55
+ verb,
56
+ route: (spec.basePath || '') + route,
57
+ operationIds,
58
+ parameters: verbs.parameters,
59
+ schemasComponents: spec.components,
60
+ headerFilters,
61
+ overrides,
62
+ });
63
+
64
+ hooks += implementation;
65
+ imports.forEach((element) => {
66
+ const formattedImport = element.replace('[]', '');
67
+ if (
68
+ !schemaImportsArray.includes(formattedImport) &&
69
+ element !== 'void' &&
70
+ element !== 'string' &&
71
+ !element.includes('{')
72
+ ) {
73
+ schemaImportsArray.push(formattedImport);
74
+ }
75
+ });
76
+ queryImports.forEach((element) => {
77
+ if (!schemaImportsArray.includes(element)) {
78
+ collectedQueryImports.push(element);
79
+ }
80
+ });
81
+ }
82
+ });
83
+ });
84
+
85
+ const imports = generateImports({
86
+ apiDirectory,
87
+ queryClientDir,
88
+ schemaName,
89
+ schemaImports: schemaImportsArray,
90
+ queryImports: collectedQueryImports,
91
+ });
92
+
93
+ writeFileSync(join(process.cwd(), `${exportDirectory}/${name}/${hooksName}.tsx`), imports + hooks);
94
+
95
+ const schemas = generateSchemas({ spec });
96
+ writeFileSync(join(process.cwd(), `${exportDirectory}/${name}/${schemaName}.tsx`), schemas);
97
+
98
+ console.log(
99
+ chalk.green(`🎉 [${filename}] Your OpenAPI spec has been converted into react query hooks`)
100
+ );
101
+ } catch (error) {
102
+ if ((error as any).code === 'EISDIR') {
103
+ console.log(chalk.red('nested folder structure not supported'));
104
+ return;
105
+ }
106
+ console.log(chalk.red(`[${filename}]:`), chalk.red(error));
107
+ }
108
+ });
109
+ });
110
+ }
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ import { convertSwaggerFile } from './convertSwaggerFile.js';
2
+ import { importSpecs } from './importSpecs.js';
3
+ export { importSpecs, convertSwaggerFile };
package/src/utils.ts ADDED
@@ -0,0 +1,190 @@
1
+ import lodash from 'lodash';
2
+ const { uniq, isEmpty } = lodash;
3
+ import pasCase from 'case';
4
+
5
+ const { pascal } = pasCase;
6
+
7
+ import { ReferenceObject, RequestBodyObject, ResponseObject, SchemaObject } from 'openapi3-ts';
8
+
9
+ export const getDocs = (data: ReferenceObject | { description?: string }) =>
10
+ isReference(data) ? '' : formatDescription(data.description);
11
+ /**
12
+ * Discriminator helper for `ReferenceObject`
13
+ */
14
+ export const isReference = (property: any): property is ReferenceObject => {
15
+ return Boolean(property.$ref);
16
+ };
17
+
18
+ /**
19
+ * Return the typescript equivalent of open-api data type
20
+ */
21
+ export const getScalar = (item: SchemaObject) => {
22
+ const nullable = item.nullable ? ' | null' : '';
23
+
24
+ switch (item.type) {
25
+ case 'number':
26
+ case 'integer':
27
+ return 'number' + nullable;
28
+
29
+ case 'boolean':
30
+ return 'boolean' + nullable;
31
+
32
+ case 'array':
33
+ return getArray(item) + nullable;
34
+
35
+ case 'string':
36
+ return (item.enum ? `"${item.enum.join(`" | "`)}"` : 'string') + nullable;
37
+
38
+ case 'object':
39
+ default:
40
+ return getObject(item) + nullable;
41
+ }
42
+ };
43
+
44
+ /**
45
+ * Return the output type from the $ref
46
+ */
47
+ const getRef = ($ref: ReferenceObject['$ref']) => {
48
+ if ($ref.startsWith('#/components/schemas')) {
49
+ return pascal($ref.replace('#/components/schemas/', ''));
50
+ } else if ($ref.startsWith('#/components/responses')) {
51
+ return pascal($ref.replace('#/components/responses/', '')) + 'Response';
52
+ } else if ($ref.startsWith('#/components/parameters')) {
53
+ return pascal($ref.replace('#/components/parameters/', '')) + 'Parameter';
54
+ } else if ($ref.startsWith('#/components/requestBodies')) {
55
+ return pascal($ref.replace('#/components/requestBodies/', '')) + 'RequestBody';
56
+ } else {
57
+ throw new Error('This library only resolve $ref that are include into `#/components/*` for now');
58
+ }
59
+ };
60
+
61
+ /**
62
+ * Return the output type from an array
63
+ */
64
+ const getArray = (item: SchemaObject): string => {
65
+ if (item.items) {
66
+ if (!isReference(item.items) && (item.items.oneOf || item.items.allOf || item.items.enum)) {
67
+ return `(${resolveValue(item.items)})[]`;
68
+ } else {
69
+ return `${resolveValue(item.items)}[]`;
70
+ }
71
+ } else {
72
+ throw new Error('All arrays must have an `items` key define');
73
+ }
74
+ };
75
+
76
+ /**
77
+ * Return the output type from an object
78
+ */
79
+ const getObject = (item: SchemaObject): string => {
80
+ if (isReference(item)) {
81
+ return getRef(item.$ref);
82
+ }
83
+
84
+ if (item.allOf) {
85
+ return item.allOf.map(resolveValue).join(' & ');
86
+ }
87
+
88
+ if (item.oneOf) {
89
+ return item.oneOf.map(resolveValue).join(' | ');
90
+ }
91
+
92
+ if (!item.type && !item.properties && !item.additionalProperties) {
93
+ return '{}';
94
+ }
95
+
96
+ // Free form object (https://swagger.io/docs/specification/data-models/data-types/#free-form)
97
+ if (
98
+ item.type === 'object' &&
99
+ !item.properties &&
100
+ (!item.additionalProperties || item.additionalProperties === true || isEmpty(item.additionalProperties))
101
+ ) {
102
+ return '{[key: string]: any}';
103
+ }
104
+
105
+ const IdentifierRegexp = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
106
+ // Consolidation of item.properties & item.additionalProperties
107
+ let output = '{\n';
108
+ if (item.properties) {
109
+ output += Object.entries(item.properties)
110
+ .map(([key, prop]: [string, ReferenceObject | SchemaObject]) => {
111
+ const doc = getDocs(prop);
112
+ const isRequired = (item.required || []).includes(key);
113
+ const processedKey = IdentifierRegexp.test(key) ? key : `"${key}"`;
114
+ return `${doc}\n${processedKey}${isRequired ? '' : '?'}: ${resolveValue(prop)};`;
115
+ })
116
+ .join('');
117
+ }
118
+
119
+ if (item.additionalProperties) {
120
+ if (item.properties) {
121
+ output += '\n';
122
+ }
123
+ output += `} & { [key: string]: ${
124
+ item.additionalProperties === true ? 'any' : resolveValue(item.additionalProperties)
125
+ }`;
126
+ }
127
+
128
+ if (item.properties || item.additionalProperties) {
129
+ if (output === '{\n') {
130
+ return '{}';
131
+ }
132
+ return output + '\n}';
133
+ }
134
+
135
+ return item.type === 'object' ? '{[key: string]: any}' : 'any';
136
+ };
137
+
138
+ /**
139
+ * Resolve the value of a schema object to a proper type definition.
140
+ */
141
+ export const resolveValue = (schema: SchemaObject) =>
142
+ isReference(schema) ? getRef(schema.$ref) : getScalar(schema);
143
+
144
+ /**
145
+ * Format a description to code documentation.
146
+ */
147
+ export const formatDescription = (description?: string) => {
148
+ if (!description) {
149
+ return '';
150
+ }
151
+ return `\n/**\n${description
152
+ .split('\n')
153
+ .map((i) => `* ${i}`)
154
+ .join('\n')}\n */`;
155
+ };
156
+
157
+ /**
158
+ * Extract responses / request types from open-api specs
159
+ */
160
+ export const getResReqTypes = (
161
+ responsesOrRequests: Array<[string, ResponseObject | ReferenceObject | RequestBodyObject]>
162
+ ) => {
163
+ return uniq(
164
+ responsesOrRequests.map(([_, res]) => {
165
+ if (!res) {
166
+ return;
167
+ }
168
+
169
+ if (isReference(res)) {
170
+ return getRef(res.$ref);
171
+ }
172
+
173
+ if (res.content) {
174
+ for (let contentType of Object.keys(res.content)) {
175
+ if (
176
+ contentType.startsWith('application/json') ||
177
+ contentType.startsWith('application/octet-stream')
178
+ ) {
179
+ const schema = res.content[contentType].schema!;
180
+
181
+ return resolveValue(schema);
182
+ }
183
+ }
184
+ return;
185
+ }
186
+
187
+ return;
188
+ })
189
+ ).join(' | ');
190
+ };