react-query-lightbase-codegen 1.0.3 → 1.0.6

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,5 @@
1
+ import { OpenAPIObject } from 'openapi3-ts';
2
+ /**
3
+ * Import and parse the openapi spec from a yaml/json
4
+ */
5
+ export declare const convertSwaggerFile: (data: string, extension: 'yaml' | 'json') => Promise<OpenAPIObject>;
@@ -0,0 +1,26 @@
1
+ import swagger2openapi from 'swagger2openapi';
2
+ import yaml from 'js-yaml';
3
+ /**
4
+ * Import and parse the openapi spec from a yaml/json
5
+ */
6
+ export const convertSwaggerFile = (data, extension) => {
7
+ const schema = extension === 'yaml' ? yaml.load(data) : JSON.parse(data);
8
+ return new Promise((resolve, reject) => {
9
+ if (!schema.openapi || !schema.openapi.startsWith('3.')) {
10
+ swagger2openapi.convertObj(schema, {}, (err, convertedObj) => {
11
+ if (err) {
12
+ reject(err);
13
+ }
14
+ else {
15
+ // @ts-ignore
16
+ convertedObj.openapi.basePath = convertedObj.original.basePath;
17
+ resolve(convertedObj.openapi);
18
+ }
19
+ });
20
+ }
21
+ else {
22
+ resolve(schema);
23
+ }
24
+ });
25
+ };
26
+ //# sourceMappingURL=convertSwaggerFile.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"convertSwaggerFile.js","sourceRoot":"","sources":["../src/convertSwaggerFile.ts"],"names":[],"mappings":"AACA,OAAO,eAAe,MAAM,iBAAiB,CAAC;AAC9C,OAAO,IAAI,MAAM,SAAS,CAAC;AAE3B;;GAEG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,IAAY,EAAE,SAA0B,EAA0B,EAAE;IACrG,MAAM,MAAM,GAAG,SAAS,KAAK,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACzE,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,IAAI,CAAC,MAAM,CAAC,OAAO,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;YACvD,eAAe,CAAC,UAAU,CAAC,MAAM,EAAE,EAAE,EAAE,CAAC,GAAG,EAAE,YAAY,EAAE,EAAE;gBAC3D,IAAI,GAAG,EAAE;oBACP,MAAM,CAAC,GAAG,CAAC,CAAC;iBACb;qBAAM;oBACL,aAAa;oBACb,YAAY,CAAC,OAAO,CAAC,QAAQ,GAAG,YAAY,CAAC,QAAQ,CAAC,QAAQ,CAAC;oBAC/D,OAAO,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;iBAC/B;YACH,CAAC,CAAC,CAAC;SACJ;aAAM;YACL,OAAO,CAAC,MAAM,CAAC,CAAC;SACjB;IACH,CAAC,CAAC,CAAC;AACL,CAAC,CAAC"}
@@ -0,0 +1,25 @@
1
+ import { ComponentsObject, OperationObject, ParameterObject, ReferenceObject } from 'openapi3-ts';
2
+ /**
3
+ * Generate a react-query component from openapi operation specs
4
+ */
5
+ export declare const createHook: ({ operation, verb, route, operationIds, parameters, schemasComponents, headerFilters, overrides, }: {
6
+ operation: OperationObject;
7
+ verb: string;
8
+ route: string;
9
+ operationIds: string[];
10
+ parameters: (ReferenceObject | ParameterObject)[] | undefined;
11
+ schemasComponents?: ComponentsObject | undefined;
12
+ headerFilters?: string[] | undefined;
13
+ overrides?: Record<string, {
14
+ type: 'query';
15
+ } | {
16
+ type: 'mutation';
17
+ } | {
18
+ type: 'infiniteQuery';
19
+ infiniteQueryParm: string;
20
+ }> | undefined;
21
+ }) => {
22
+ implementation: string;
23
+ imports: string[];
24
+ queryImports: ("query" | "mutation" | "infiniteQuery")[];
25
+ };
@@ -0,0 +1,393 @@
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 fetchName = camel(componentName);
120
+ const createQueryHooks = (emptyParams) => {
121
+ const params = emptyParams ? '' : `params: ${componentName}Params,`;
122
+ const key = emptyParams ? '' : `params`;
123
+ const mutationParams = emptyParams ? 'void' : `${componentName}Params`;
124
+ const queryParamType = emptyParams ? '' : `${componentName}Params &`;
125
+ const filterParams = emptyParams
126
+ ? '{ filters }: { filters?: QueryFilters }'
127
+ : `{ params, filters }: { params: ${componentName}Params, filters?: QueryFilters }`;
128
+ const cacheParams = emptyParams
129
+ ? `{updater, options}: {updater: Updater<${responseTypes} | undefined, ${responseTypes} | undefined>, options?: SetDataOptions | undefined}`
130
+ : `{params, updater, options}: {params: ${componentName}Params, updater: Updater<${responseTypes} | undefined, ${responseTypes} | undefined>, options?: SetDataOptions | undefined}`;
131
+ const queryKey = emptyParams
132
+ ? `use${componentName}Query.baseKey()`
133
+ : `[...use${componentName}Query.baseKey(), params]`;
134
+ const createQuery = () => `
135
+ type ${componentName}QueryProps<T = ${responseTypes}> = ${queryParamType} {
136
+ options?: UseQueryOptions<${responseTypes}, AxiosError, T, any>
137
+ }
138
+ export function use${componentName}Query<T = ${responseTypes}>({ options = {}, ...params }: ${componentName}QueryProps<T>) {
139
+ return useQuery(use${componentName}Query.queryKey(${key}), async () => ${fetchName}(${key}), { enabled: ${enabledParam}, ...options });
140
+ }
141
+
142
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
143
+
144
+ use${componentName}Query.queryKey = (${params}): QueryKey => ${queryKey};
145
+
146
+ use${componentName}Query.updateCache = (${cacheParams}) => queryClient.setQueryData<${responseTypes}>(use${componentName}Query.queryKey(${key}), updater, options);
147
+
148
+ use${componentName}Query.getQueryState = (${filterParams})=> queryClient.getQueryState<${responseTypes}>(use${componentName}Query.queryKey(${key}), filters);
149
+
150
+ use${componentName}Query.getQueryData = (${filterParams})=> queryClient.getQueryData<${responseTypes}>(use${componentName}Query.queryKey(${key}), filters);
151
+
152
+ use${componentName}Query.prefetch = (${params}) => queryClient.prefetchQuery<${responseTypes}>(use${componentName}Query.queryKey(${key}), ()=> ${fetchName}(${key}));
153
+
154
+ use${componentName}Query.cancelQueries = (${params}) => queryClient.cancelQueries(use${componentName}Query.queryKey(${key}))
155
+
156
+ use${componentName}Query.invalidate = (${params}) => queryClient.invalidateQueries<${responseTypes}>(use${componentName}Query.queryKey(${key}));
157
+
158
+ use${componentName}Query.refetchStale = (${params}) => queryClient.refetchQueries<${responseTypes}>(use${componentName}Query.queryKey(${key}), { stale: true });
159
+ `;
160
+ const getInfiniteQuery = ({ pageParam }) => `
161
+ type ${componentName}QueryProps<T = ${responseTypes}> = ${queryParamType} {
162
+ options: UseInfiniteQueryOptions<${responseTypes}, AxiosError, T, any>
163
+ }
164
+ export function use${componentName}Query<T = ${responseTypes}>({ options = {}, ...params }: ${componentName}QueryProps<T>) {
165
+ return useInfiniteQuery(use${componentName}Query.queryKey(${key}), async ({ pageParam = 0 }) => ${fetchName}({${pageParam}: pageParam, ...params}), { enabled: ${enabledParam}, ...options });
166
+ }
167
+
168
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
169
+
170
+ use${componentName}Query.queryKey = (${params}): QueryKey => ${queryKey};
171
+
172
+ `;
173
+ const createMutation = () => `
174
+ type ${componentName}MutationProps<T> = {
175
+ options?: UseMutationOptions<${responseTypes}, AxiosError, ${mutationParams}, T>
176
+ }
177
+ export function use${componentName}Mutation<T = ${responseTypes}>(props?: ${componentName}MutationProps<T>) {
178
+ return useMutation(async (${key}) => ${fetchName}(${key}), props?.options)
179
+ };
180
+ `;
181
+ const override = overrides?.[operationId];
182
+ if (override?.type === 'query') {
183
+ console.log(chalk.blue(`⚙️ [${operationId}] has been changed to a useQuery hook`));
184
+ queryImports.push('query');
185
+ return createQuery();
186
+ }
187
+ if (override?.type === 'mutation') {
188
+ queryImports.push('mutation');
189
+ console.log(chalk.blue(`⚙️ [${operationId}] has been changed to a useMutation hook`));
190
+ return createMutation();
191
+ }
192
+ if (override?.type === 'infiniteQuery') {
193
+ console.log(chalk.blue(`⚙️ [${operationId}] has been changed to a useInfiniteQuery hook`));
194
+ queryImports.push('infiniteQuery');
195
+ return getInfiniteQuery({ pageParam: override.infiniteQueryParm });
196
+ }
197
+ if (verb === 'get') {
198
+ queryImports.push('query');
199
+ return createQuery();
200
+ }
201
+ queryImports.push('mutation');
202
+ return createMutation();
203
+ };
204
+ output += createQueryHooks(!requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam);
205
+ const hasRequestBodyArrray = requestBodyComponent && requestBodyComponent.includes('[]');
206
+ const body = hasRequestBodyArrray ? `{body: ${requestBodyComponent}}` : `${requestBodyComponent}`;
207
+ const bodyProps = hasRequestBodyArrray ? `{body, ...props}` : '{props}';
208
+ const generateProps = (props) => {
209
+ return props.map((item) => `["${item.name}"]: props["${item.name}"]`).join(',');
210
+ };
211
+ const generateBodyProps = () => {
212
+ const definitionKey = Object.keys(schemasComponents?.schemas || {}).find((key) => pascal(key) === requestBodyComponent);
213
+ if (definitionKey && !hasRequestBodyArrray) {
214
+ const scheme = schemasComponents?.schemas?.[definitionKey];
215
+ const generatedBodyProps = Object.keys(scheme.properties)
216
+ .map((item) => `["${item}"]: props["${item}"]`)
217
+ .join(',');
218
+ return `const body = {${generatedBodyProps}}`;
219
+ }
220
+ return '';
221
+ };
222
+ if (!requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
223
+ output += `
224
+ const ${fetchName} = async () => {
225
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`);
226
+ return result.data;
227
+ }
228
+ `;
229
+ }
230
+ if (!requestBodyComponent && paramsInPath.length && queryParam && !headerParam) {
231
+ const config = isUpdateRequest ? 'body,{params}' : '{params}';
232
+ output += `
233
+ type ${componentName}Params = {
234
+ ${paramsTypes}
235
+ ${queryParamsType};
236
+ }
237
+
238
+ const ${fetchName} = async (props:${componentName}Params) => {
239
+ const {${paramsInPath.join(', ')}, ...params} = props
240
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config})
241
+ return result.data;
242
+ }`;
243
+ }
244
+ if (!requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
245
+ output += `
246
+ type ${componentName}Params = {
247
+ ${paramsTypes}
248
+ }
249
+
250
+ const ${fetchName} = async (props: ${componentName}Params ) => {
251
+ const result = await api.${verb}<${responseTypes}>(\`${route.replace(/\{/g, '{props.')}\`);
252
+ return result.data;
253
+ }
254
+ `;
255
+ }
256
+ if (!requestBodyComponent && !paramsInPath.length && queryParam && !headerParam) {
257
+ const config = isUpdateRequest ? 'null,{params}' : '{params}';
258
+ output += `
259
+ type ${componentName}Params = {
260
+ ${queryParamsType}
261
+ }
262
+
263
+ const ${fetchName} = async (params: ${componentName}Params) => {
264
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config})
265
+ return result.data;
266
+ }
267
+ `;
268
+ }
269
+ if (!requestBodyComponent && !paramsInPath.length && queryParam && headerParam) {
270
+ const config = isUpdateRequest ? 'null,{headers, params: queryParams}' : '{headers, params: queryParams}';
271
+ output += `
272
+ type ${componentName}Params = {
273
+ ${headerParam}
274
+ ${queryParamsType}
275
+ }
276
+ const ${fetchName} = async (props: ${componentName}Params) => {
277
+ const headers = {${generateProps(header)}}
278
+ const queryParams = {${generateProps(queryParams)}}
279
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config})
280
+ return result.data
281
+ }`;
282
+ }
283
+ if (!requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
284
+ const config = isUpdateRequest ? 'null,{headers}' : '{headers}';
285
+ output += `
286
+ type ${componentName}Params = {
287
+ ${headerParam}
288
+ };
289
+
290
+ const ${fetchName} = async (headers: ${componentName}Params) => {
291
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config});
292
+ return result.data;
293
+ }
294
+ `;
295
+ }
296
+ if (requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
297
+ output += `
298
+ type ${componentName}Params = ${requestBodyComponent}
299
+
300
+ const ${fetchName} = async (body: ${componentName}Params) => {
301
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, body)
302
+ return result.data
303
+ }
304
+ `;
305
+ }
306
+ if (requestBodyComponent && !paramsInPath.length && queryParam && !headerParam) {
307
+ output += `
308
+ type ${componentName}Params = ${body} & {
309
+ ${queryParamsType}
310
+ }
311
+
312
+ const ${fetchName} = async (${bodyProps}: ${componentName}Params) => {
313
+ ${generateBodyProps()}
314
+ const params = {${generateProps(queryParams)}}
315
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, body, {params})
316
+ return result.data
317
+ }
318
+ `;
319
+ }
320
+ if (requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
321
+ output += `
322
+ type ${componentName}Params = ${body} & {
323
+ ${headerParam}
324
+ };
325
+
326
+ const ${fetchName} = async (${bodyProps}: ${componentName}Params) => {
327
+ ${generateBodyProps()}
328
+ const headers = {${generateProps(header)}}
329
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, body, {headers})
330
+ return result.data
331
+ }
332
+ `;
333
+ }
334
+ if (requestBodyComponent && !paramsInPath.length && queryParam && headerParam) {
335
+ output += `
336
+ type ${componentName}Params = ${body} & {
337
+ ${headerParam}
338
+ ${paramsTypes}
339
+ };
340
+
341
+ const ${fetchName} = async (${bodyProps}: ${componentName}Params) => {
342
+ ${generateBodyProps()}
343
+ const headers = {${generateProps(header)}}
344
+ const params = {${generateProps(queryParams)}}
345
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, body, {headers, params})
346
+ return result.data
347
+ }
348
+ `;
349
+ }
350
+ if (requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
351
+ output += `
352
+ type ${componentName}Params = ${body} & {
353
+ ${headerParam}
354
+ ${paramsTypes}
355
+ };
356
+
357
+ const ${fetchName} = async (${bodyProps}: ${componentName}Params) => {
358
+ ${generateBodyProps()}
359
+ const result = await api.${verb}<${responseTypes}>(\`${route.replace(/\{/g, '{props.')}\`, body)
360
+ return result.data
361
+ }
362
+ `;
363
+ }
364
+ if (requestBodyComponent && paramsInPath.length && queryParam && !headerParam) {
365
+ output += `// TODO: NOT SUPPORTED requestBodyComponent && paramsInPath && queryParam)`;
366
+ }
367
+ if (requestBodyComponent && paramsInPath.length && queryParam && headerParam) {
368
+ output += `// TODO: NOT SUPPORTED requestBodyComponent && paramsInPath && queryParam && headerParam)`;
369
+ }
370
+ if (!requestBodyComponent && paramsInPath.length && !queryParam && headerParam) {
371
+ const config = isUpdateRequest ? 'null,{headers}' : '{headers}';
372
+ output += `
373
+ type ${componentName}Params = {
374
+ ${headerParam}
375
+ ${paramsTypes}
376
+ };
377
+
378
+ const ${fetchName} = async (props: ${componentName}Params) => {
379
+ const headers = {${generateProps(header)}}
380
+ const result = await api.${verb}<${responseTypes}>(\`${route.replace(/\{/g, '{props.')}\`, ${config})
381
+ return result.data
382
+ }
383
+ `;
384
+ }
385
+ if (!requestBodyComponent && paramsInPath.length && queryParam && headerParam) {
386
+ output += `// TODO: NOT SUPPORTED (paramsInPath && queryParam && headerParam)`;
387
+ }
388
+ if (requestBodyComponent && paramsInPath.length && !queryParam && headerParam) {
389
+ output += `// TODO: NOT SUPPORTED (requestBodyComponent && paramsInPath && headerParam)`;
390
+ }
391
+ return { implementation: output, imports, queryImports };
392
+ };
393
+ //# sourceMappingURL=generateHooks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generateHooks.js","sourceRoot":"","sources":["../src/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;;;KAGpG,CAAC;KACH;IAED,IAAI,CAAC,oBAAoB,IAAI,YAAY,CAAC,MAAM,IAAI,UAAU,IAAI,WAAW,EAAE;QAC7E,MAAM,IAAI,oEAAoE,CAAC;KAChF;IAED,IAAI,oBAAoB,IAAI,YAAY,CAAC,MAAM,IAAI,CAAC,UAAU,IAAI,WAAW,EAAE;QAC7E,MAAM,IAAI,8EAA8E,CAAC;KAC1F;IAED,OAAO,EAAE,cAAc,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,EAAE,CAAC;AAC3D,CAAC,CAAC"}
@@ -0,0 +1,7 @@
1
+ export declare const generateImports: ({ schemaName, apiDirectory, queryClientDir, schemaImports, queryImports, }: {
2
+ apiDirectory: string;
3
+ queryClientDir: string;
4
+ schemaName: string;
5
+ schemaImports: string[];
6
+ queryImports: ('query' | 'mutation' | 'infiniteQuery')[];
7
+ }) => string;
@@ -0,0 +1,28 @@
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
+ };
28
+ //# sourceMappingURL=generateImports.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generateImports.js","sourceRoot":"","sources":["../src/generateImports.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,EAC9B,UAAU,EACV,YAAY,EACZ,cAAc,EACd,aAAa,EACb,YAAY,GAOb,EAAE,EAAE;IACH,MAAM,WAAW,GAAG,aAAa,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC5C,IAAI,OAAO,GAAG,EAAc,CAAC;IAC7B,IAAI,YAAY,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE;QAClC,OAAO,GAAG,CAAC,GAAG,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,UAAU,EAAE,gBAAgB,EAAE,cAAc,CAAC,CAAC;KACrG;IACD,IAAI,YAAY,CAAC,QAAQ,CAAC,eAAe,CAAC,EAAE;QAC1C,OAAO,GAAG,CAAC,GAAG,OAAO,EAAE,kBAAkB,EAAE,yBAAyB,EAAE,UAAU,CAAC,CAAC;KACnF;IACD,IAAI,YAAY,CAAC,QAAQ,CAAC,UAAU,CAAC,EAAE;QACrC,OAAO,GAAG,CAAC,GAAG,OAAO,EAAE,oBAAoB,EAAE,aAAa,CAAC,CAAC;KAC7D;IAED,MAAM,YAAY,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAErD,OAAO;;MAEH,YAAY;;;;yBAIO,YAAY;iCACJ,cAAc;;YAEnC,WAAW,aAAa,UAAU;;;GAG3C,CAAC;AACJ,CAAC,CAAC"}
@@ -0,0 +1,7 @@
1
+ import { OpenAPIObject } from 'openapi3-ts';
2
+ /**
3
+ * Extract all types from #/components/schemas
4
+ */
5
+ export declare const generateSchemas: ({ spec }: {
6
+ spec: OpenAPIObject;
7
+ }) => string;
@@ -0,0 +1,97 @@
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
+ };
97
+ //# sourceMappingURL=generateSchemas.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generateSchemas.js","sourceRoot":"","sources":["../src/generateSchemas.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,MAAM,CAAC;AAC3B,OAAO,MAAM,MAAM,QAAQ,CAAC;AAC5B,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC;AAC3B,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;AAE3B,OAAO,EAAE,iBAAiB,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAErF,OAAO,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAErD;;GAEG;AACH,MAAM,iBAAiB,GAAG,CAAC,IAAY,EAAE,MAAoB,EAAE,EAAE;IAC/D,MAAM,MAAM,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC;IACjC,OAAO,GAAG,iBAAiB,CAAC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pB,OAAO,iBAAiB,MAAM,CAAC,IAAI,CAAC,cAAc,IAAI,EAAE,CAAC;aAC1D;iBAAM,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE;gBAC3E,OAAO,GAAG,GAAG,iBAAiB,MAAM,CAAC,IAAI,CAAC,cAAc,IAAI,EAAE,CAAC;aAChE;iBAAM;gBACL,OAAO,GAAG,GAAG,iBAAiB,MAAM,CAAC,IAAI,CAAC,cAAc,IAAI,GAAG,CAAC;aACjE;QACH,CAAC,CAAC;aACD,IAAI,CAAC,MAAM,CAAC;QACf,IAAI,CACL,CAAC;AACJ,CAAC,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,EAAE,IAAI,EAA2B,EAAE,EAAE;IACnE,MAAM,YAAY,GAChB,+BAA+B,CAAC,IAAI,CAAC,UAAU,EAAE,aAAa,CAAC;QAC/D,2BAA2B,CAAC,IAAI,CAAC,UAAU,EAAE,SAAS,CAAC;QACvD,yBAAyB,CAAC,IAAI,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;IAEtD,OAAO,YAAY,CAAC;AACtB,CAAC,CAAC"}
@@ -0,0 +1,15 @@
1
+ export declare function importSpecs({ sourceDirectory, exportDirectory, apiDirectory, queryClientDir, headerFilters, overrides, }: {
2
+ sourceDirectory: string;
3
+ exportDirectory: string;
4
+ apiDirectory: string;
5
+ queryClientDir: string;
6
+ headerFilters?: string[];
7
+ overrides?: Record<string, {
8
+ type: 'query';
9
+ } | {
10
+ type: 'mutation';
11
+ } | {
12
+ type: 'infiniteQuery';
13
+ infiniteQueryParm: string;
14
+ }>;
15
+ }): void;
@@ -0,0 +1,83 @@
1
+ import Case from 'case';
2
+ import chalk from 'chalk';
3
+ import { readFileSync, writeFileSync, readdir, mkdirSync } from 'fs';
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
+ export function importSpecs({ sourceDirectory, exportDirectory, apiDirectory, queryClientDir, headerFilters, overrides, }) {
10
+ readdir(sourceDirectory, function (err, filenames) {
11
+ if (err) {
12
+ console.log(err);
13
+ throw err;
14
+ }
15
+ filenames.map(async (filename) => {
16
+ try {
17
+ const data = readFileSync(join(process.cwd(), sourceDirectory + '/' + filename), 'utf-8');
18
+ const { ext } = parse(sourceDirectory + '/' + filename);
19
+ const format = ['.yaml', '.yml'].includes(ext.toLowerCase()) ? 'yaml' : 'json';
20
+ let spec = await convertSwaggerFile(data, format);
21
+ const formattedFileName = Case.camel(`useQueries, ${filename.split('.')[0]}`);
22
+ const schemaName = `${formattedFileName}.schema`;
23
+ const hooksName = `${formattedFileName}`;
24
+ const name = filename.split('.')[0];
25
+ mkdirSync(join(process.cwd(), `${exportDirectory}/${name}`), { recursive: true });
26
+ const operationIds = [];
27
+ let hooks = '';
28
+ let schemaImportsArray = [];
29
+ let collectedQueryImports = [];
30
+ Object.entries(spec.paths).forEach(([route, verbs]) => {
31
+ Object.entries(verbs).forEach(([verb, operation]) => {
32
+ if (['get', 'post', 'patch', 'put', 'delete'].includes(verb) && !operation.deprecated) {
33
+ const { implementation, imports, queryImports } = createHook({
34
+ operation,
35
+ verb,
36
+ route: (spec.basePath || '') + route,
37
+ operationIds,
38
+ parameters: verbs.parameters,
39
+ schemasComponents: spec.components,
40
+ headerFilters,
41
+ overrides,
42
+ });
43
+ hooks += implementation;
44
+ imports.forEach((element) => {
45
+ const formattedImport = element.replace('[]', '');
46
+ if (!schemaImportsArray.includes(formattedImport) &&
47
+ element !== 'void' &&
48
+ element !== 'string' &&
49
+ !element.includes('{')) {
50
+ schemaImportsArray.push(formattedImport);
51
+ }
52
+ });
53
+ queryImports.forEach((element) => {
54
+ if (!schemaImportsArray.includes(element)) {
55
+ collectedQueryImports.push(element);
56
+ }
57
+ });
58
+ }
59
+ });
60
+ });
61
+ const imports = generateImports({
62
+ apiDirectory,
63
+ queryClientDir,
64
+ schemaName,
65
+ schemaImports: schemaImportsArray,
66
+ queryImports: collectedQueryImports,
67
+ });
68
+ writeFileSync(join(process.cwd(), `${exportDirectory}/${name}/${hooksName}.tsx`), imports + hooks);
69
+ const schemas = generateSchemas({ spec });
70
+ writeFileSync(join(process.cwd(), `${exportDirectory}/${name}/${schemaName}.tsx`), schemas);
71
+ console.log(chalk.green(`🎉 [${filename}] Your OpenAPI spec has been converted into react query hooks`));
72
+ }
73
+ catch (error) {
74
+ if (error.code === 'EISDIR') {
75
+ console.log(chalk.red('nested folder structure not supported'));
76
+ return;
77
+ }
78
+ console.log(chalk.red(`[${filename}]:`), chalk.red(error));
79
+ }
80
+ });
81
+ });
82
+ }
83
+ //# sourceMappingURL=importSpecs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"importSpecs.js","sourceRoot":"","sources":["../src/importSpecs.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AAErE,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,MAAM,CAAC;AACnC,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAEvD,MAAM,UAAU,WAAW,CAAC,EAC1B,eAAe,EACf,eAAe,EACf,YAAY,EACZ,cAAc,EACd,aAAa,EACb,SAAS,GAWV;IACC,OAAO,CAAC,eAAe,EAA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+ import { importSpecs } from './importSpecs.js';
3
+ export { importSpecs, convertSwaggerFile };
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ import { convertSwaggerFile } from './convertSwaggerFile.js';
2
+ import { importSpecs } from './importSpecs.js';
3
+ export { importSpecs, convertSwaggerFile };
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,WAAW,EAAE,kBAAkB,EAAE,CAAC"}
@@ -0,0 +1,24 @@
1
+ import { ReferenceObject, RequestBodyObject, ResponseObject, SchemaObject } from 'openapi3-ts';
2
+ export declare const getDocs: (data: ReferenceObject | {
3
+ description?: string;
4
+ }) => string;
5
+ /**
6
+ * Discriminator helper for `ReferenceObject`
7
+ */
8
+ export declare const isReference: (property: any) => property is ReferenceObject;
9
+ /**
10
+ * Return the typescript equivalent of open-api data type
11
+ */
12
+ export declare const getScalar: (item: SchemaObject) => string;
13
+ /**
14
+ * Resolve the value of a schema object to a proper type definition.
15
+ */
16
+ export declare const resolveValue: (schema: SchemaObject) => string;
17
+ /**
18
+ * Format a description to code documentation.
19
+ */
20
+ export declare const formatDescription: (description?: string) => string;
21
+ /**
22
+ * Extract responses / request types from open-api specs
23
+ */
24
+ export declare const getResReqTypes: (responsesOrRequests: Array<[string, ResponseObject | ReferenceObject | RequestBodyObject]>) => string;
package/dist/utils.js ADDED
@@ -0,0 +1,157 @@
1
+ import lodash from 'lodash';
2
+ const { uniq, isEmpty } = lodash;
3
+ import pasCase from 'case';
4
+ const { pascal } = pasCase;
5
+ export const getDocs = (data) => isReference(data) ? '' : formatDescription(data.description);
6
+ /**
7
+ * Discriminator helper for `ReferenceObject`
8
+ */
9
+ export const isReference = (property) => {
10
+ return Boolean(property.$ref);
11
+ };
12
+ /**
13
+ * Return the typescript equivalent of open-api data type
14
+ */
15
+ export const getScalar = (item) => {
16
+ const nullable = item.nullable ? ' | null' : '';
17
+ switch (item.type) {
18
+ case 'number':
19
+ case 'integer':
20
+ return 'number' + nullable;
21
+ case 'boolean':
22
+ return 'boolean' + nullable;
23
+ case 'array':
24
+ return getArray(item) + nullable;
25
+ case 'string':
26
+ return (item.enum ? `"${item.enum.join(`" | "`)}"` : 'string') + nullable;
27
+ case 'object':
28
+ default:
29
+ return getObject(item) + nullable;
30
+ }
31
+ };
32
+ /**
33
+ * Return the output type from the $ref
34
+ */
35
+ const getRef = ($ref) => {
36
+ if ($ref.startsWith('#/components/schemas')) {
37
+ return pascal($ref.replace('#/components/schemas/', ''));
38
+ }
39
+ else if ($ref.startsWith('#/components/responses')) {
40
+ return pascal($ref.replace('#/components/responses/', '')) + 'Response';
41
+ }
42
+ else if ($ref.startsWith('#/components/parameters')) {
43
+ return pascal($ref.replace('#/components/parameters/', '')) + 'Parameter';
44
+ }
45
+ else if ($ref.startsWith('#/components/requestBodies')) {
46
+ return pascal($ref.replace('#/components/requestBodies/', '')) + 'RequestBody';
47
+ }
48
+ else {
49
+ throw new Error('This library only resolve $ref that are include into `#/components/*` for now');
50
+ }
51
+ };
52
+ /**
53
+ * Return the output type from an array
54
+ */
55
+ const getArray = (item) => {
56
+ if (item.items) {
57
+ if (!isReference(item.items) && (item.items.oneOf || item.items.allOf || item.items.enum)) {
58
+ return `(${resolveValue(item.items)})[]`;
59
+ }
60
+ else {
61
+ return `${resolveValue(item.items)}[]`;
62
+ }
63
+ }
64
+ else {
65
+ throw new Error('All arrays must have an `items` key define');
66
+ }
67
+ };
68
+ /**
69
+ * Return the output type from an object
70
+ */
71
+ const getObject = (item) => {
72
+ if (isReference(item)) {
73
+ return getRef(item.$ref);
74
+ }
75
+ if (item.allOf) {
76
+ return item.allOf.map(resolveValue).join(' & ');
77
+ }
78
+ if (item.oneOf) {
79
+ return item.oneOf.map(resolveValue).join(' | ');
80
+ }
81
+ if (!item.type && !item.properties && !item.additionalProperties) {
82
+ return '{}';
83
+ }
84
+ // Free form object (https://swagger.io/docs/specification/data-models/data-types/#free-form)
85
+ if (item.type === 'object' &&
86
+ !item.properties &&
87
+ (!item.additionalProperties || item.additionalProperties === true || isEmpty(item.additionalProperties))) {
88
+ return '{[key: string]: any}';
89
+ }
90
+ const IdentifierRegexp = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
91
+ // Consolidation of item.properties & item.additionalProperties
92
+ let output = '{\n';
93
+ if (item.properties) {
94
+ output += Object.entries(item.properties)
95
+ .map(([key, prop]) => {
96
+ const doc = getDocs(prop);
97
+ const isRequired = (item.required || []).includes(key);
98
+ const processedKey = IdentifierRegexp.test(key) ? key : `"${key}"`;
99
+ return `${doc}\n${processedKey}${isRequired ? '' : '?'}: ${resolveValue(prop)};`;
100
+ })
101
+ .join('');
102
+ }
103
+ if (item.additionalProperties) {
104
+ if (item.properties) {
105
+ output += '\n';
106
+ }
107
+ output += `} & { [key: string]: ${item.additionalProperties === true ? 'any' : resolveValue(item.additionalProperties)}`;
108
+ }
109
+ if (item.properties || item.additionalProperties) {
110
+ if (output === '{\n') {
111
+ return '{}';
112
+ }
113
+ return output + '\n}';
114
+ }
115
+ return item.type === 'object' ? '{[key: string]: any}' : 'any';
116
+ };
117
+ /**
118
+ * Resolve the value of a schema object to a proper type definition.
119
+ */
120
+ export const resolveValue = (schema) => isReference(schema) ? getRef(schema.$ref) : getScalar(schema);
121
+ /**
122
+ * Format a description to code documentation.
123
+ */
124
+ export const formatDescription = (description) => {
125
+ if (!description) {
126
+ return '';
127
+ }
128
+ return `\n/**\n${description
129
+ .split('\n')
130
+ .map((i) => `* ${i}`)
131
+ .join('\n')}\n */`;
132
+ };
133
+ /**
134
+ * Extract responses / request types from open-api specs
135
+ */
136
+ export const getResReqTypes = (responsesOrRequests) => {
137
+ return uniq(responsesOrRequests.map(([_, res]) => {
138
+ if (!res) {
139
+ return;
140
+ }
141
+ if (isReference(res)) {
142
+ return getRef(res.$ref);
143
+ }
144
+ if (res.content) {
145
+ for (let contentType of Object.keys(res.content)) {
146
+ if (contentType.startsWith('application/json') ||
147
+ contentType.startsWith('application/octet-stream')) {
148
+ const schema = res.content[contentType].schema;
149
+ return resolveValue(schema);
150
+ }
151
+ }
152
+ return;
153
+ }
154
+ return;
155
+ })).join(' | ');
156
+ };
157
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAC5B,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC;AACjC,OAAO,OAAO,MAAM,MAAM,CAAC;AAE3B,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;AAI3B,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,IAAgD,EAAE,EAAE,CAC1E,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,iBAAiB,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;AAC/D;;GAEG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,QAAa,EAA+B,EAAE;IACxE,OAAO,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;AAChC,CAAC,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,IAAkB,EAAE,EAAE;IAC9C,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC;IAEhD,QAAQ,IAAI,CAAC,IAAI,EAAE;QACjB,KAAK,QAAQ,CAAC;QACd,KAAK,SAAS;YACZ,OAAO,QAAQ,GAAG,QAAQ,CAAC;QAE7B,KAAK,SAAS;YACZ,OAAO,SAAS,GAAG,QAAQ,CAAC;QAE9B,KA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AAY,CAAC,MAAM,CAAC,CAAC;iBAC7B;aACF;YACD,OAAO;SACR;QAED,OAAO;IACT,CAAC,CAAC,CACH,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAChB,CAAC,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
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.3",
4
+ "version": "1.0.6",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "exports": "./dist/index.js",
@@ -38,6 +38,7 @@
38
38
  "lint": "eslint . --ext .js,.jsx,.ts,.tsx",
39
39
  "tsc": "tsc -p tsconfig.json",
40
40
  "test": "yarn tsc && node test/script.mjs && prettier --check ./test/generated/**/*.tsx --write && eslint ./test/generated/**/*.tsx --fix",
41
+ "deploy": "tsc && semantic-release --no-ci",
41
42
  "prepare": "husky install"
42
43
  },
43
44
  "dependencies": {
@@ -183,22 +183,6 @@ export const createHook = ({
183
183
 
184
184
  const isUpdateRequest = ['post', 'patch', 'put'].includes(verb);
185
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
186
  const fetchName = camel(componentName);
203
187
 
204
188
  const createQueryHooks = (emptyParams?: boolean) => {
@@ -296,6 +280,28 @@ export const createHook = ({
296
280
 
297
281
  output += createQueryHooks(!requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam);
298
282
 
283
+ const hasRequestBodyArrray = requestBodyComponent && requestBodyComponent.includes('[]');
284
+ const body = hasRequestBodyArrray ? `{body: ${requestBodyComponent}}` : `${requestBodyComponent}`;
285
+ const bodyProps = hasRequestBodyArrray ? `{body, ...props}` : '{props}';
286
+
287
+ const generateProps = (props: ParameterObject[]) => {
288
+ return props.map((item) => `["${item.name}"]: props["${item.name}"]`).join(',');
289
+ };
290
+
291
+ const generateBodyProps = () => {
292
+ const definitionKey = Object.keys(schemasComponents?.schemas || {}).find(
293
+ (key) => pascal(key) === requestBodyComponent
294
+ );
295
+ if (definitionKey && !hasRequestBodyArrray) {
296
+ const scheme = schemasComponents?.schemas?.[definitionKey] as SchemaObject;
297
+ const generatedBodyProps = Object.keys(scheme.properties as SchemaObject)
298
+ .map((item: string) => `["${item}"]: props["${item}"]`)
299
+ .join(',');
300
+ return `const body = {${generatedBodyProps}}`;
301
+ }
302
+ return '';
303
+ };
304
+
299
305
  if (!requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
300
306
  output += `
301
307
  const ${fetchName} = async () => {
@@ -386,22 +392,15 @@ export const createHook = ({
386
392
  }
387
393
 
388
394
  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
395
  output += `
392
- type ${componentName}Params = ${requestBodyComponent} & {
393
- ${queryParamsType}
394
- }
396
+ type ${componentName}Params = ${body} & {
397
+ ${queryParamsType}
398
+ }
395
399
 
396
- type ${componentName}QueryProps<T = ${responseTypes}> = ${componentName}Params & {
397
- const body = {${generateBodyProps()}}
400
+ const ${fetchName} = async (${bodyProps}: ${componentName}Params) => {
401
+ ${generateBodyProps()}
398
402
  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})
403
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, body, {params})
405
404
  return result.data
406
405
  }
407
406
  `;
@@ -409,13 +408,13 @@ export const createHook = ({
409
408
 
410
409
  if (requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
411
410
  output += `
412
- type ${componentName}Params = ${requestBodyComponent} & {
411
+ type ${componentName}Params = ${body} & {
413
412
  ${headerParam}
414
413
  };
415
414
 
416
- const ${fetchName} = async (props: ${componentName}Params) => {
415
+ const ${fetchName} = async (${bodyProps}: ${componentName}Params) => {
416
+ ${generateBodyProps()}
417
417
  const headers = {${generateProps(header)}}
418
- const body = {${generateBodyProps()}}
419
418
  const result = await api.${verb}<${responseTypes}>(\`${route}\`, body, {headers})
420
419
  return result.data
421
420
  }
@@ -424,13 +423,13 @@ export const createHook = ({
424
423
 
425
424
  if (requestBodyComponent && !paramsInPath.length && queryParam && headerParam) {
426
425
  output += `
427
- type ${componentName}Params = ${requestBodyComponent} & {
426
+ type ${componentName}Params = ${body} & {
428
427
  ${headerParam}
429
428
  ${paramsTypes}
430
429
  };
431
430
 
432
- const ${fetchName} = async (props: ${componentName}Params) => {
433
- const body = {${generateBodyProps()}}
431
+ const ${fetchName} = async (${bodyProps}: ${componentName}Params) => {
432
+ ${generateBodyProps()}
434
433
  const headers = {${generateProps(header)}}
435
434
  const params = {${generateProps(queryParams)}}
436
435
  const result = await api.${verb}<${responseTypes}>(\`${route}\`, body, {headers, params})
@@ -441,13 +440,13 @@ export const createHook = ({
441
440
 
442
441
  if (requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
443
442
  output += `
444
- type ${componentName}Params = ${requestBodyComponent} & {
443
+ type ${componentName}Params = ${body} & {
445
444
  ${headerParam}
446
445
  ${paramsTypes}
447
446
  };
448
447
 
449
- const ${fetchName} = async (props: ${componentName}Params) => {
450
- const body = {${generateBodyProps()}}
448
+ const ${fetchName} = async (${bodyProps}: ${componentName}Params) => {
449
+ ${generateBodyProps()}
451
450
  const result = await api.${verb}<${responseTypes}>(\`${route.replace(/\{/g, '{props.')}\`, body)
452
451
  return result.data
453
452
  }
@@ -1,3 +1,4 @@
1
+ import Case from 'case';
1
2
  import chalk from 'chalk';
2
3
  import { readFileSync, writeFileSync, readdir, mkdirSync } from 'fs';
3
4
  import { OperationObject, PathItemObject } from 'openapi3-ts';
@@ -37,8 +38,9 @@ export function importSpecs({
37
38
  const format = ['.yaml', '.yml'].includes(ext.toLowerCase()) ? 'yaml' : 'json';
38
39
  let spec = await convertSwaggerFile(data, format);
39
40
 
40
- const schemaName = `useQueries${filename.split('.')[0]}.schema`;
41
- const hooksName = `useQueries${filename.split('.')[0]}`;
41
+ const formattedFileName = Case.camel(`useQueries, ${filename.split('.')[0]}`);
42
+ const schemaName = `${formattedFileName}.schema`;
43
+ const hooksName = `${formattedFileName}`;
42
44
  const name = filename.split('.')[0];
43
45
  mkdirSync(join(process.cwd(), `${exportDirectory}/${name}`), { recursive: true });
44
46