react-query-lightbase-codegen 1.1.1 → 1.1.4

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.
@@ -1,360 +0,0 @@
1
- import lodash from 'lodash';
2
- const { get, groupBy, uniq } = lodash;
3
- import { formatDescription, getResReqTypes, isReference, resolveValue } from './utils.js';
4
- import pasCase from 'case';
5
- const { pascal } = pasCase;
6
- const IdentifierRegexp = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
7
- /**
8
- * Return every params in a path
9
- */
10
- const getParamsInPath = (path) => {
11
- let n;
12
- const output = [];
13
- const templatePathRegex = /\{(\w+)}/g;
14
- while ((n = templatePathRegex.exec(path)) !== null) {
15
- output.push(n[1]);
16
- }
17
- return output;
18
- };
19
- const createQueryHooks = ({ componentName, responseTypes, enabledParam, emptyParams, }) => {
20
- const params = emptyParams ? '' : `params: ${componentName}Params,`;
21
- const key = emptyParams ? '' : `params`;
22
- const mutationParams = emptyParams ? 'void' : `${componentName}Params`;
23
- const queryParams = emptyParams ? '' : `${componentName}Params &`;
24
- const filterParams = emptyParams
25
- ? '{ filters }: { filters?: QueryFilters }'
26
- : `{ params, filters }: { params: ${componentName}Params, filters }`;
27
- const cacheParams = emptyParams
28
- ? `{updater, options}: {updater: Updater<${responseTypes} | undefined, ${responseTypes} | undefined>, options?: SetDataOptions | undefined}`
29
- : `{params, updater, options}: {params: ${componentName}Params, updater: Updater<${responseTypes} | undefined, ${responseTypes} | undefined>, options?: SetDataOptions | undefined}`;
30
- const queryKey = emptyParams
31
- ? `use${componentName}Query.baseKey()`
32
- : `[...use${componentName}Query.baseKey(), params]`;
33
- const query = `
34
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
35
-
36
- use${componentName}Query.queryKey = (${params}): QueryKey => ${queryKey};
37
-
38
- use${componentName}Query.updateCache = (${cacheParams}) => queryClient.setQueryData<${responseTypes}>(use${componentName}Query.queryKey(${key}), updater, options);
39
-
40
- use${componentName}Query.getQueryState = (${filterParams})=> queryClient.getQueryState<${responseTypes}>(use${componentName}Query.queryKey(${key}), filters);
41
-
42
- use${componentName}Query.getQueryData = (${filterParams})=> queryClient.getQueryData<${responseTypes}>(use${componentName}Query.queryKey(${key}), filters);
43
-
44
- use${componentName}Query.prefetch = (${params}) => queryClient.prefetchQuery<${responseTypes}>(use${componentName}Query.queryKey(${key}), ()=> use${componentName}Query.fetch(${key}));
45
-
46
- use${componentName}Query.cancelQueries = (${params}) => queryClient.cancelQueries(use${componentName}Query.queryKey(${key}))
47
-
48
- use${componentName}Query.invalidate = (${params}) => queryClient.invalidateQueries<${responseTypes}>(use${componentName}Query.queryKey(${key}));
49
-
50
- use${componentName}Query.refetchStale = (${params}) => queryClient.refetchQueries<${responseTypes}>(use${componentName}Query.queryKey(${key}), { stale: true });
51
-
52
- type ${componentName}QueryProps<T = ${responseTypes}> = ${queryParams} {
53
- options?: UseQueryOptions<${responseTypes}, AxiosError, T, any>
54
- }
55
- export function use${componentName}Query<T = ${responseTypes}>({ options = {}, ...params }: ${componentName}QueryProps<T>) {
56
- return useQuery(use${componentName}Query.queryKey(${key}), async () => use${componentName}Query.fetch(${key}), { enabled: ${enabledParam}, ...options });
57
- }`;
58
- const mutation = `
59
- type ${componentName}MutationProps<T> = {
60
- options?: UseMutationOptions<${responseTypes}, AxiosError, ${mutationParams}, T>
61
- }
62
- export function use${componentName}Mutation<T = ${responseTypes}>(props?: ${componentName}MutationProps<T>) {
63
- return useMutation(async (${key}) => use${componentName}Query.fetch(${key}), props?.options)
64
- };`;
65
- return query + mutation;
66
- };
67
- /**
68
- * Generate a react-query component from openapi operation specs
69
- */
70
- const createHook = ({ operation, verb, route, operationIds, parameters, schemasComponents, headerFilters, }) => {
71
- const { operationId = route.replace('/', '') } = operation;
72
- if (operationId === '*') {
73
- throw new Error(`Invalid operationId/Route set for ${verb} ${route}`);
74
- }
75
- if (operationIds.includes(operationId)) {
76
- throw new Error(`"${operationId}" is duplicated in your schema definition!`);
77
- }
78
- operationIds.push(operationId);
79
- route = route.replace(/\{/g, '${').replace('//', '/'); // `/pet/{id}` => `/pet/${id}`
80
- // Remove the last param of the route if we are in the DELETE case
81
- let lastParamInTheRoute = null;
82
- const componentName = pascal(operationId);
83
- const isOk = ([statusCode]) => statusCode.toString().startsWith('2');
84
- const responseTypes = getResReqTypes(Object.entries(operation.responses).filter(isOk)) || 'void';
85
- const requestBodyTypes = getResReqTypes([['body', operation.requestBody]]);
86
- let imports = [responseTypes];
87
- const paramsInPath = getParamsInPath(route).filter((param) => !(verb === 'delete' && param === lastParamInTheRoute));
88
- const { query: queryParams = [], path: pathParams = [], header = [], } = groupBy([...(parameters || []), ...(operation.parameters || [])].map((p) => {
89
- if (isReference(p)) {
90
- return get(schemasComponents, p.$ref.replace('#/components/', '').replace('/', '.'));
91
- }
92
- else {
93
- return p;
94
- }
95
- }), 'in');
96
- const headerParams = header.filter((p) => !headerFilters?.includes(p.name));
97
- let enabled = [];
98
- // TODO: extract all requestBody or remove useQuery variants
99
- let enabledParam = '!!params';
100
- [...queryParams, ...pathParams, ...headerParams].forEach((item) => {
101
- if (item.required) {
102
- enabled.push(`["${item.name}"]`);
103
- if (enabledParam && enabledParam !== '!!params') {
104
- enabledParam += `&& params['${item.name}'] != null`;
105
- }
106
- else {
107
- enabledParam = `params['${item.name}'] != null`;
108
- }
109
- }
110
- });
111
- // `!props${enabled.join('== null && !props')}`;
112
- const paramsTypes = paramsInPath
113
- .map((p) => {
114
- try {
115
- const { name, required, schema } = pathParams.find((i) => i.name === p);
116
- return `${name}${required ? '' : '?'}: ${resolveValue(schema)}`;
117
- }
118
- catch (err) {
119
- throw new Error(`The path params ${p} can't be found in parameters (${operationId})`);
120
- }
121
- })
122
- .join('; ');
123
- const queryParamsType = queryParams
124
- .map((p) => {
125
- const processedName = IdentifierRegexp.test(p.name) ? p.name : `"${p.name}"`;
126
- return `${formatDescription(p.description)}${processedName}${p.required ? '' : '?'}: ${resolveValue(p.schema)}`;
127
- })
128
- .join(';\n ');
129
- const headerType = headerParams
130
- .map((p) => {
131
- try {
132
- const { name, required, schema } = headerParams.find((i) => i.name === p.name);
133
- return `"${name}"${required ? '' : '?'}: ${resolveValue(schema)}`;
134
- }
135
- catch (err) {
136
- throw new Error(`The path params ${p} can't be found in parameters (${operationId})`);
137
- }
138
- })
139
- .join('; ');
140
- // Retrieve the type of the param for delete verb
141
- const lastParamInTheRouteDefinition = operation.parameters && lastParamInTheRoute
142
- ? operation.parameters.find((p) => {
143
- if (isReference(p)) {
144
- return false;
145
- }
146
- return p.name === lastParamInTheRoute;
147
- }) // Reference is not possible
148
- : { schema: { type: 'string' } };
149
- if (!lastParamInTheRouteDefinition) {
150
- throw new Error(`The path params ${lastParamInTheRoute} can't be found in parameters (${operationId})`);
151
- }
152
- const description = formatDescription(operation.summary && operation.description
153
- ? `${operation.summary}\n\n${operation.description}`
154
- : `${operation.summary || ''}${operation.description || ''}`);
155
- let output = `\n\n${description}`;
156
- const headerParam = headerType && headerType !== 'void' ? `${headerType};` : '';
157
- const queryParam = queryParamsType && queryParamsType !== 'void' ? `${queryParamsType}` : '';
158
- const requestBodyComponent = requestBodyTypes && requestBodyTypes !== 'void' ? `${requestBodyTypes}` : '';
159
- if (requestBodyComponent) {
160
- imports.push(requestBodyComponent);
161
- }
162
- // QUERIES
163
- if (!requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
164
- output += `
165
- // SECTION-A
166
- use${componentName}Query.fetch = async () => {
167
- const result = await api.${verb}<${responseTypes}>(\`${route}\`);
168
- return result.data;
169
- }
170
- `;
171
- output += createQueryHooks({ componentName, responseTypes, enabledParam, emptyParams: true });
172
- }
173
- if (!requestBodyComponent && paramsInPath.length && queryParam && !headerParam) {
174
- output += `
175
- // SECTION-B
176
- type ${componentName}Params = {
177
- ${paramsTypes}
178
- ${queryParamsType};
179
- }
180
-
181
- use${componentName}Query.fetch = async (props:${componentName}Params) => {
182
- const {${paramsInPath.join(', ')}, ...params} = props
183
- const result = await api.${verb}<${responseTypes}>(\`${route}\`, {params})
184
- return result.data;
185
- }`;
186
- output += createQueryHooks({ componentName, responseTypes, enabledParam });
187
- }
188
- if (!requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
189
- output += `
190
- // SECTION-C
191
- type ${componentName}Params = {
192
- ${paramsTypes}
193
- }
194
-
195
- use${componentName}Query.fetch = async (props: ${componentName}Params ) => {
196
- const result = await api.${verb}<${responseTypes}>(\`${route.replace(/\{/g, '{props.')}\`);
197
- return result.data;
198
- }
199
- `;
200
- output += createQueryHooks({ componentName, responseTypes, enabledParam });
201
- }
202
- if (!requestBodyComponent && !paramsInPath.length && queryParam && !headerParam) {
203
- output += `
204
- // SECTION-D
205
- type ${componentName}Params = {
206
- ${queryParamsType}
207
- }
208
-
209
- use${componentName}Query.fetch = async (props: ${componentName}Params) => {
210
- const result = await api.${verb}<${responseTypes}>(\`${route}\`, {params: props})
211
- return result.data;
212
- }
213
- `;
214
- output += createQueryHooks({ componentName, responseTypes, enabledParam });
215
- }
216
- if (requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
217
- output += `
218
- // SECTION-E
219
- type ${componentName}Params = ${requestBodyComponent}
220
-
221
- use${componentName}Query.fetch = async (body: ${componentName}Params) => {
222
- const result = await api.${verb}<${responseTypes}>(\`${route}\`, body)
223
- return result.data
224
- }
225
-
226
- `;
227
- output += createQueryHooks({ componentName, responseTypes, enabledParam });
228
- }
229
- if (requestBodyComponent && !paramsInPath.length && queryParam && !headerParam) {
230
- output += `
231
- // SECTION-G
232
- // TODO: LOOKS BROKEN
233
- type ${componentName}Params = {
234
- body: ${requestBodyComponent}
235
- queryParams: ${queryParamsType}
236
- }
237
-
238
- type ${componentName}QueryProps<T = ${responseTypes}> = ${componentName}Params & {
239
- options?: UseQueryOptions<${responseTypes}, AxiosError, T, any>
240
- }
241
-
242
- use${componentName}Query.fetch = async ({body, queryParams}: ${componentName}Params) => {
243
- const result = await api.${verb}<${responseTypes}>(\`${route}\`, body, {params: queryParams})
244
- return result.data
245
- }
246
- `;
247
- output += createQueryHooks({ componentName, responseTypes, enabledParam });
248
- }
249
- if (!requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
250
- output += `
251
- // SECTION-H
252
- type ${componentName}Params = {
253
- ${headerParam}
254
- };
255
-
256
- use${componentName}Query.fetch = async (headers: ${componentName}Params) => {
257
- const result = await api.${verb}<${responseTypes}>(\`${route}\`, {headers});
258
- return result.data;
259
- }
260
- `;
261
- output += createQueryHooks({ componentName, responseTypes, enabledParam });
262
- }
263
- if (requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
264
- output += `
265
- // SECTION-J
266
- type ${componentName}Params = {
267
- body: ${requestBodyComponent}
268
- headers: {${headerParam}}
269
- };
270
-
271
- use${componentName}Query.fetch = async ({headers, body}: ${componentName}Params) => {
272
- const result = await api.${verb}<${responseTypes}>(\`${route}\`, body, {headers})
273
- return result.data
274
- }`;
275
- output += createQueryHooks({ componentName, responseTypes, enabledParam });
276
- }
277
- if (!requestBodyComponent && !paramsInPath.length && queryParam && headerParam) {
278
- output += `
279
- // SECTION-K
280
- type ${componentName}Params = {
281
- headers: {${headerParam}}
282
- queryParams: {${queryParamsType} }
283
- }
284
- use${componentName}Query.fetch = async ({headers, queryParams}: ${componentName}Params) => {
285
- const result = await api.${verb}<${responseTypes}>(\`${route}\`, body, {headers, params: queryParams})
286
- return result.data
287
- }`;
288
- output += createQueryHooks({ componentName, responseTypes, enabledParam });
289
- }
290
- if (requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
291
- output += `// TODO: NOT SUPPORTED requestBodyComponent && paramsInPath)`;
292
- }
293
- if (requestBodyComponent && paramsInPath.length && queryParam && !headerParam) {
294
- output += `// TODO: NOT SUPPORTED requestBodyComponent && paramsInPath && queryParam)`;
295
- }
296
- if (requestBodyComponent && !paramsInPath.length && queryParam && headerParam) {
297
- output += `// TODO: NOT SUPPORTED requestBodyComponent && queryParam && headerParam)`;
298
- }
299
- if (requestBodyComponent && paramsInPath.length && queryParam && headerParam) {
300
- output += `// TODO: NOT SUPPORTED requestBodyComponent && paramsInPath && queryParam && headerParam)`;
301
- }
302
- if (!requestBodyComponent && paramsInPath.length && !queryParam && headerParam) {
303
- output += `// TODO: NOT SUPPORTED (paramsInPath && headerParam)`;
304
- }
305
- if (!requestBodyComponent && paramsInPath.length && queryParam && headerParam) {
306
- output += `// TODO: NOT SUPPORTED (paramsInPath && queryParam && headerParam)`;
307
- }
308
- if (requestBodyComponent && paramsInPath.length && !queryParam && headerParam) {
309
- output += `// TODO: NOT SUPPORTED (requestBodyComponent && paramsInPath && headerParam)`;
310
- }
311
- return { implementation: output, imports };
312
- };
313
- export const generateImports = ({ schemaName, apiDirectory, queryClientDir, schemaImports, }) => {
314
- const importTypes = schemaImports.join(',');
315
- return `
316
- import {
317
- useQuery,
318
- useMutation,
319
- UseQueryOptions,
320
- UseMutationOptions,
321
- QueryKey,
322
- SetDataOptions,
323
- QueryFilters
324
- } from '@tanstack/react-query';
325
-
326
- import { AxiosError } from 'axios';
327
- import { api } from '${apiDirectory}';
328
- import { queryClient } from '${queryClientDir}';
329
-
330
- import {${importTypes}} from './${schemaName}'
331
-
332
- type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput);
333
- `;
334
- };
335
- export const generateQueryHooks = ({ spec, operationIds, headerFilters, }) => {
336
- const { paths, components } = spec;
337
- let hooks = '';
338
- let schemaImports = [];
339
- Object.entries(paths).forEach(([route, verbs]) => {
340
- Object.entries(verbs).forEach(([verb, operation]) => {
341
- if (['get', 'post', 'patch', 'put', 'delete'].includes(verb) && !operation.deprecated) {
342
- const { implementation, imports } = createHook({
343
- operation,
344
- verb,
345
- route: spec.basePath + route,
346
- operationIds,
347
- parameters: verbs.parameters,
348
- schemasComponents: components,
349
- headerFilters,
350
- });
351
- hooks += implementation;
352
- imports.forEach((element) => {
353
- schemaImports.push(element.replace('[]', ''));
354
- });
355
- }
356
- });
357
- });
358
- const schemaImportsFiltered = schemaImports.filter((item) => !!item && item !== 'void' && item !== 'boolean' && item !== 'undefined' && item !== 'string');
359
- return { implementation: hooks, schemaImports: uniq(schemaImportsFiltered) };
360
- };
@@ -1,22 +0,0 @@
1
- export const generateImports = ({ schemaName, apiDirectory, queryClientDir, schemaImports, }) => {
2
- const importTypes = schemaImports.join(',');
3
- return `
4
- import {
5
- useQuery,
6
- useMutation,
7
- UseQueryOptions,
8
- UseMutationOptions,
9
- QueryKey,
10
- SetDataOptions,
11
- QueryFilters
12
- } from '@tanstack/react-query';
13
-
14
- import { AxiosError } from 'axios';
15
- import { api } from '${apiDirectory}';
16
- import { queryClient } from '${queryClientDir}';
17
-
18
- import {${importTypes}} from './${schemaName}'
19
-
20
- type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput);
21
- `;
22
- };
@@ -1,39 +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 { generateImports, generateQueryHooks } from './generateHooks.js';
6
- import { generateSchemas } from './generateSchemas.js';
7
- export function importSpecs({ sourceDirectory, exportDirectory, apiDirectory, queryClientDir, headerFilters, }) {
8
- readdir(sourceDirectory, function (err, filenames) {
9
- if (err) {
10
- console.log(err);
11
- throw err;
12
- }
13
- filenames.map(async (filename) => {
14
- try {
15
- const data = readFileSync(join(process.cwd(), sourceDirectory + '/' + filename), 'utf-8');
16
- const { ext } = parse(sourceDirectory + '/' + filename);
17
- const format = ['.yaml', '.yml'].includes(ext.toLowerCase()) ? 'yaml' : 'json';
18
- const name = filename.split('.')[0];
19
- let spec = await convertSwaggerFile(data, format);
20
- const operationIds = [];
21
- mkdirSync(join(process.cwd(), `${exportDirectory}/${name}`), { recursive: true });
22
- const { implementation, schemaImports } = generateQueryHooks({ spec, operationIds, headerFilters });
23
- const schemaName = `useQueries${filename.split('.')[0]}.schema`;
24
- const imports = generateImports({ apiDirectory, queryClientDir, schemaName, schemaImports });
25
- const hooksName = `useQueries${filename.split('.')[0]}`;
26
- writeFileSync(join(process.cwd(), `${exportDirectory}/${name}/${hooksName}.tsx`), imports + implementation);
27
- const schemas = generateSchemas({ spec });
28
- writeFileSync(join(process.cwd(), `${exportDirectory}/${name}/${schemaName}.tsx`), schemas);
29
- console.log(chalk.green(`🎉 [${filename}] Your OpenAPI spec has been converted into react query hooks`));
30
- }
31
- catch (error) {
32
- if (error.code === 'EISDIR') {
33
- return;
34
- }
35
- console.log(chalk.red(`[${filename}]:`), chalk.red(error));
36
- }
37
- });
38
- });
39
- }