react-query-lightbase-codegen 0.3.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +76 -0
  2. package/lib/commonjs/convertSwaggerFile.js +37 -0
  3. package/lib/commonjs/convertSwaggerFile.js.map +1 -0
  4. package/lib/commonjs/generateHooks.js +492 -0
  5. package/lib/commonjs/generateHooks.js.map +1 -0
  6. package/lib/commonjs/generateImports.js +48 -0
  7. package/lib/commonjs/generateImports.js.map +1 -0
  8. package/lib/commonjs/generateSchemas.js +119 -0
  9. package/lib/commonjs/generateSchemas.js.map +1 -0
  10. package/lib/commonjs/importSpecs.js +117 -0
  11. package/lib/commonjs/importSpecs.js.map +1 -0
  12. package/lib/commonjs/index.js +22 -0
  13. package/lib/commonjs/index.js.map +1 -0
  14. package/lib/commonjs/utils.js +212 -0
  15. package/lib/commonjs/utils.js.map +1 -0
  16. package/lib/src/convertSwaggerFile.js +29 -0
  17. package/lib/src/generateHooks.js +249 -0
  18. package/lib/src/generateImports.js +29 -0
  19. package/lib/src/generateSchemas.js +108 -0
  20. package/lib/src/importSpecs.js +134 -0
  21. package/lib/src/index.js +7 -0
  22. package/lib/src/utils.js +172 -0
  23. package/lib/typescript/convertSwaggerFile.d.ts +5 -0
  24. package/lib/typescript/generateHooks.d.ts +25 -0
  25. package/lib/typescript/generateImports.d.ts +7 -0
  26. package/lib/typescript/generateSchemas.d.ts +7 -0
  27. package/lib/typescript/importSpecs.d.ts +15 -0
  28. package/lib/typescript/index.d.ts +3 -0
  29. package/lib/typescript/utils.d.ts +24 -0
  30. package/package.json +71 -17
  31. package/src/convertSwaggerFile.ts +25 -0
  32. package/src/generateHooks.ts +490 -0
  33. package/src/generateImports.ts +41 -0
  34. package/src/generateSchemas.ts +114 -0
  35. package/src/importSpecs.ts +110 -0
  36. package/src/index.ts +3 -0
  37. package/src/utils.ts +190 -0
  38. package/lib/cjs/import-open-api.js +0 -1034
  39. package/lib/cjs/index.js +0 -5
  40. package/lib/cjs/react-query-codegen-import.js +0 -41
  41. package/lib/cjs/types.js +0 -2
  42. package/lib/esm/import-open-api.js +0 -1012
  43. package/lib/esm/index.js +0 -2
  44. package/lib/esm/react-query-codegen-import.js +0 -34
  45. package/lib/esm/types.js +0 -1
@@ -1,1012 +0,0 @@
1
- import { pascal } from 'case';
2
- import get from 'lodash/get';
3
- import groupBy from 'lodash/groupBy';
4
- import isEmpty from 'lodash/isEmpty';
5
- import set from 'lodash/set';
6
- import uniq from 'lodash/uniq';
7
- import swagger2openapi from 'swagger2openapi';
8
- const yaml = require('js-yaml');
9
- const IdentifierRegexp = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
10
- /**
11
- * Import and parse the openapi spec from a yaml/json
12
- */
13
- const importSpecs = (data, extension) => {
14
- const schema = extension === 'yaml' ? yaml.load(data) : JSON.parse(data);
15
- return new Promise((resolve, reject) => {
16
- if (!schema.openapi || !schema.openapi.startsWith('3.')) {
17
- swagger2openapi.convertObj(schema, {}, (err, convertedObj) => {
18
- if (err) {
19
- reject(err);
20
- }
21
- else {
22
- // @ts-ignore
23
- convertedObj.openapi.basePath = convertedObj.original.basePath;
24
- resolve(convertedObj.openapi);
25
- }
26
- });
27
- }
28
- else {
29
- resolve(schema);
30
- }
31
- });
32
- };
33
- /**
34
- * Discriminator helper for `ReferenceObject`
35
- */
36
- export const isReference = (property) => {
37
- return Boolean(property.$ref);
38
- };
39
- /**
40
- * Return the typescript equivalent of open-api data type
41
- */
42
- export const getScalar = (item) => {
43
- const nullable = item.nullable ? ' | null' : '';
44
- switch (item.type) {
45
- case 'number':
46
- case 'integer':
47
- return 'number' + nullable;
48
- case 'boolean':
49
- return 'boolean' + nullable;
50
- case 'array':
51
- return getArray(item) + nullable;
52
- case 'string':
53
- return (item.enum ? `"${item.enum.join(`" | "`)}"` : 'string') + nullable;
54
- case 'object':
55
- default:
56
- return getObject(item) + nullable;
57
- }
58
- };
59
- /**
60
- * Return the output type from the $ref
61
- */
62
- export const getRef = ($ref) => {
63
- if ($ref.startsWith('#/components/schemas')) {
64
- return pascal($ref.replace('#/components/schemas/', ''));
65
- }
66
- else if ($ref.startsWith('#/components/responses')) {
67
- return pascal($ref.replace('#/components/responses/', '')) + 'Response';
68
- }
69
- else if ($ref.startsWith('#/components/parameters')) {
70
- return pascal($ref.replace('#/components/parameters/', '')) + 'Parameter';
71
- }
72
- else if ($ref.startsWith('#/components/requestBodies')) {
73
- return pascal($ref.replace('#/components/requestBodies/', '')) + 'RequestBody';
74
- }
75
- else {
76
- throw new Error('This library only resolve $ref that are include into `#/components/*` for now');
77
- }
78
- };
79
- /**
80
- * Return the output type from an array
81
- */
82
- export const getArray = (item) => {
83
- if (item.items) {
84
- if (!isReference(item.items) && (item.items.oneOf || item.items.allOf || item.items.enum)) {
85
- return `(${resolveValue(item.items)})[]`;
86
- }
87
- else {
88
- return `${resolveValue(item.items)}[]`;
89
- }
90
- }
91
- else {
92
- throw new Error('All arrays must have an `items` key define');
93
- }
94
- };
95
- /**
96
- * Return the output type from an object
97
- */
98
- export const getObject = (item) => {
99
- if (isReference(item)) {
100
- return getRef(item.$ref);
101
- }
102
- if (item.allOf) {
103
- return item.allOf.map(resolveValue).join(' & ');
104
- }
105
- if (item.oneOf) {
106
- return item.oneOf.map(resolveValue).join(' | ');
107
- }
108
- if (!item.type && !item.properties && !item.additionalProperties) {
109
- return '{}';
110
- }
111
- // Free form object (https://swagger.io/docs/specification/data-models/data-types/#free-form)
112
- if (item.type === 'object' &&
113
- !item.properties &&
114
- (!item.additionalProperties || item.additionalProperties === true || isEmpty(item.additionalProperties))) {
115
- return '{[key: string]: any}';
116
- }
117
- // Consolidation of item.properties & item.additionalProperties
118
- let output = '{\n';
119
- if (item.properties) {
120
- output += Object.entries(item.properties)
121
- .map(([key, prop]) => {
122
- const doc = isReference(prop) ? '' : formatDescription(prop.description, 2);
123
- const isRequired = (item.required || []).includes(key);
124
- const processedKey = IdentifierRegexp.test(key) ? key : `"${key}"`;
125
- return `${doc}\n${processedKey}${isRequired ? '' : '?'}: ${resolveValue(prop)};`;
126
- })
127
- .join('\n');
128
- }
129
- if (item.additionalProperties) {
130
- if (item.properties) {
131
- output += '\n';
132
- }
133
- output += `} & { [key: string]: ${item.additionalProperties === true ? 'any' : resolveValue(item.additionalProperties)}`;
134
- }
135
- if (item.properties || item.additionalProperties) {
136
- if (output === '{\n') {
137
- return '{}';
138
- }
139
- return output + '\n}';
140
- }
141
- return item.type === 'object' ? '{[key: string]: any}' : 'any';
142
- };
143
- /**
144
- * Resolve the value of a schema object to a proper type definition.
145
- */
146
- export const resolveValue = (schema) => isReference(schema) ? getRef(schema.$ref) : getScalar(schema);
147
- /**
148
- * Extract responses / request types from open-api specs
149
- */
150
- export const getResReqTypes = (responsesOrRequests) => uniq(responsesOrRequests.map(([_, res]) => {
151
- if (!res) {
152
- return 'void';
153
- }
154
- if (isReference(res)) {
155
- return getRef(res.$ref);
156
- }
157
- if (res.content) {
158
- for (let contentType of Object.keys(res.content)) {
159
- if (contentType.startsWith('application/json') ||
160
- contentType.startsWith('application/octet-stream')) {
161
- const schema = res.content[contentType].schema;
162
- return resolveValue(schema);
163
- }
164
- }
165
- return 'void';
166
- }
167
- return 'void';
168
- })).join(' | ');
169
- /**
170
- * Return every params in a path
171
- *
172
- * @example
173
- * ```
174
- * getParamsInPath("/pet/{category}/{name}/");
175
- * // => ["category", "name"]
176
- * ```
177
- */
178
- export const getParamsInPath = (path) => {
179
- let n;
180
- const output = [];
181
- const templatePathRegex = /\{(\w+)}/g;
182
- while ((n = templatePathRegex.exec(path)) !== null) {
183
- output.push(n[1]);
184
- }
185
- return output;
186
- };
187
- /**
188
- * Generate the interface string
189
- */
190
- export const generateInterface = (name, schema) => {
191
- const scalar = getScalar(schema);
192
- return `
193
- ${formatDescription(schema.description)}
194
- export type ${pascal(name)} = ${scalar}
195
- `;
196
- };
197
- /**
198
- * Propagate every `discriminator.propertyName` mapping to the original ref
199
- *
200
- * Note: This method directly mutate the `specs` object.
201
- */
202
- export const resolveDiscriminator = (specs) => {
203
- if (specs.components && specs.components.schemas) {
204
- Object.values(specs.components.schemas).forEach((schema) => {
205
- if (isReference(schema) || !schema.discriminator || !schema.discriminator.mapping) {
206
- return;
207
- }
208
- const { mapping, propertyName } = schema.discriminator;
209
- Object.entries(mapping).forEach(([name, ref]) => {
210
- if (!ref.startsWith('#/components/schemas/')) {
211
- throw new Error('Discriminator mapping outside of `#/components/schemas` is not supported');
212
- }
213
- set(specs, `components.schemas.${ref.slice('#/components/schemas/'.length)}.properties.${propertyName}.enum`, [name]);
214
- });
215
- });
216
- }
217
- };
218
- /**
219
- * Extract all types from #/components/schemas
220
- */
221
- export const generateSchemasDefinition = (schemas = {}) => {
222
- if (isEmpty(schemas)) {
223
- return '';
224
- }
225
- return (Object.entries(schemas)
226
- .map(([name, schema]) => !isReference(schema) &&
227
- (!schema.type || schema.type === 'object') &&
228
- !schema.allOf &&
229
- !schema.oneOf &&
230
- !isReference(schema) &&
231
- !schema.nullable
232
- ? generateInterface(name, schema)
233
- : `${formatDescription(isReference(schema) ? undefined : schema.description)}export type ${pascal(name)} = ${resolveValue(schema)};`)
234
- .join('\n\n') + '\n');
235
- };
236
- /**
237
- * Extract all types from #/components/requestBodies
238
- */
239
- export const generateRequestBodiesDefinition = (requestBodies = {}) => {
240
- if (isEmpty(requestBodies)) {
241
- return '';
242
- }
243
- return ('\n' +
244
- Object.entries(requestBodies)
245
- .map(([name, requestBody]) => {
246
- const doc = isReference(requestBody) ? '' : formatDescription(requestBody.description);
247
- const type = getResReqTypes([['', requestBody]]);
248
- const isEmptyInterface = type === '{}';
249
- if (isEmptyInterface) {
250
- return `export type ${pascal(name)}RequestBody = ${type}`;
251
- }
252
- else if (type.includes('{') && !type.includes('|') && !type.includes('&')) {
253
- return `${doc}export type ${pascal(name)}RequestBody = ${type}`;
254
- }
255
- else {
256
- return `${doc}export type ${pascal(name)}RequestBody = ${type};`;
257
- }
258
- })
259
- .join('\n\n') +
260
- '\n');
261
- };
262
- /**
263
- * Extract all types from #/components/responses
264
- */
265
- export const generateResponsesDefinition = (responses = {}) => {
266
- if (isEmpty(responses)) {
267
- return '';
268
- }
269
- return ('\n' +
270
- Object.entries(responses)
271
- .map(([name, response]) => {
272
- const doc = isReference(response) ? '' : formatDescription(response.description);
273
- const type = getResReqTypes([['', response]]);
274
- const isEmptyInterface = type === '{}';
275
- if (isEmptyInterface) {
276
- return `export type RQ${pascal(name)}Response = ${type}`;
277
- }
278
- else if (type.includes('{') && !type.includes('|') && !type.includes('&')) {
279
- return `${doc}export type RQ${pascal(name)}Response = ${type}`;
280
- }
281
- else {
282
- return `${doc}export type RQ${pascal(name)}Response = ${type};`;
283
- }
284
- })
285
- .join('\n\n') +
286
- '\n');
287
- };
288
- /**
289
- * Format a description to code documentation.
290
- */
291
- export const formatDescription = (description, tabSize = 0) => description
292
- ? `/**\n${description
293
- .split('\n')
294
- .map((i) => `${' '.repeat(tabSize)} * ${i}`)
295
- .join('\n')}\n${' '.repeat(tabSize)} */${' '.repeat(tabSize)}`
296
- : '';
297
- /**
298
- * Generate a react-query component from openapi operation specs
299
- */
300
- export const generateRestfulComponent = ({ operation, verb, route, operationIds, parameters, schemasComponents, headerFilters, }) => {
301
- const { operationId = route.replace('/', '') } = operation;
302
- if (operationId === '*') {
303
- throw new Error(`Invalid operationId/Route set for ${verb} ${route}`);
304
- }
305
- if (operationIds.includes(operationId)) {
306
- throw new Error(`"${operationId}" is duplicated in your schema definition!`);
307
- }
308
- operationIds.push(operationId);
309
- route = route.replace(/\{/g, '${').replace('//', '/'); // `/pet/{id}` => `/pet/${id}`
310
- // Remove the last param of the route if we are in the DELETE case
311
- let lastParamInTheRoute = null;
312
- const componentName = pascal(operationId);
313
- const isOk = ([statusCode]) => statusCode.toString().startsWith('2');
314
- const responseTypes = getResReqTypes(Object.entries(operation.responses).filter(isOk)) || 'void';
315
- const requestBodyTypes = getResReqTypes([['body', operation.requestBody]]);
316
- const needAResponseComponent = true;
317
- const paramsInPath = getParamsInPath(route).filter((param) => !(verb === 'delete' && param === lastParamInTheRoute));
318
- const { query: queryParams = [], path: pathParams = [], header = [], } = groupBy([...(parameters || []), ...(operation.parameters || [])].map((p) => {
319
- if (isReference(p)) {
320
- return get(schemasComponents, p.$ref.replace('#/components/', '').replace('/', '.'));
321
- }
322
- else {
323
- return p;
324
- }
325
- }), 'in');
326
- const headerParams = header.filter((p) => !headerFilters?.includes(p.name));
327
- let enabled = [];
328
- // TODO: extract all requestBody or remove useQuery variants
329
- let enabledParam = '!!props';
330
- [...queryParams, ...pathParams, ...headerParams].forEach((item) => {
331
- if (item.required) {
332
- enabled.push(`["${item.name}"]`);
333
- if (enabledParam && enabledParam !== '!!props') {
334
- enabledParam += `&& props['${item.name}'] != null`;
335
- }
336
- else {
337
- enabledParam = `props['${item.name}'] != null`;
338
- }
339
- }
340
- });
341
- // `!props${enabled.join('== null && !props')}`;
342
- const paramsTypes = paramsInPath
343
- .map((p) => {
344
- try {
345
- const { name, required, schema } = pathParams.find((i) => i.name === p);
346
- return `${name}${required ? '' : '?'}: ${resolveValue(schema)}`;
347
- }
348
- catch (err) {
349
- throw new Error(`The path params ${p} can't be found in parameters (${operationId})`);
350
- }
351
- })
352
- .join('; ');
353
- const queryParamsType = queryParams
354
- .map((p) => {
355
- const processedName = IdentifierRegexp.test(p.name) ? p.name : `"${p.name}"`;
356
- return `${formatDescription(p.description, 2)}${processedName}${p.required ? '' : '?'}: ${resolveValue(p.schema)}`;
357
- })
358
- .join(';\n ');
359
- const headerType = headerParams
360
- .map((p) => {
361
- try {
362
- const { name, required, schema } = headerParams.find((i) => i.name === p.name);
363
- return `"${name}"${required ? '' : '?'}: ${resolveValue(schema)}`;
364
- }
365
- catch (err) {
366
- throw new Error(`The path params ${p} can't be found in parameters (${operationId})`);
367
- }
368
- })
369
- .join('; ');
370
- // Retrieve the type of the param for delete verb
371
- const lastParamInTheRouteDefinition = operation.parameters && lastParamInTheRoute
372
- ? operation.parameters.find((p) => {
373
- if (isReference(p)) {
374
- return false;
375
- }
376
- return p.name === lastParamInTheRoute;
377
- }) // Reference is not possible
378
- : { schema: { type: 'string' } };
379
- if (!lastParamInTheRouteDefinition) {
380
- throw new Error(`The path params ${lastParamInTheRoute} can't be found in parameters (${operationId})`);
381
- }
382
- let genericsTypes = `${needAResponseComponent ? componentName + 'Res' : responseTypes}`;
383
- if (verb !== 'get') {
384
- genericsTypes = `${needAResponseComponent ? componentName + 'Res' : responseTypes}`;
385
- }
386
- const description = formatDescription(operation.summary && operation.description
387
- ? `${operation.summary}\n\n${operation.description}`
388
- : `${operation.summary || ''}${operation.description || ''}`);
389
- let output = `\n\n${description}`;
390
- const typeOrInterface = `type ${componentName}Res =`;
391
- output += `
392
- ${needAResponseComponent ? `export ${typeOrInterface} ${responseTypes}` : ''}
393
- `;
394
- const headerParam = headerType && headerType !== 'void' ? `${headerType};` : '';
395
- const queryParam = queryParamsType && queryParamsType !== 'void' ? `${queryParamsType}` : '';
396
- const requestBodyComponent = requestBodyTypes && requestBodyTypes !== 'void' ? `${requestBodyTypes}` : '';
397
- // QUERIES
398
- if (!requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
399
- output += `
400
- type ${componentName}Return = ${genericsTypes}
401
- type ${componentName}Variables = {
402
- ${paramsTypes}
403
- }
404
-
405
- use${componentName}Query.fetch = async (props: ${componentName}Variables ) => {
406
- const result = await api.${verb}<${componentName}Return>(\`${route.replace(/\{/g, '{props.')}\`);
407
- return result.data;
408
- }
409
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
410
- use${componentName}Query.queryKey = (params: ${componentName}Variables ): QueryKey => [...use${componentName}Query.baseKey(), params];
411
-
412
- use${componentName}Query.updateCache = (
413
- {params, updater, options}:
414
- {params: ${componentName}Variables,
415
- updater: Updater<${componentName}Return | undefined, ${componentName}Return | undefined>,
416
- options?: SetDataOptions | undefined}
417
- ) => queryClient.setQueryData<${componentName}Return>(use${componentName}Query.queryKey(params), updater, options);
418
-
419
- use${componentName}Query.getQueryState = ({params, filters}:{params: ${componentName}Variables, filters?: QueryFilters})=> queryClient.getQueryState<${componentName}Return>(use${componentName}Query.queryKey(params), filters);
420
- use${componentName}Query.getQueryData = ({params, filters}:{params: ${componentName}Variables, filters?: QueryFilters})=> queryClient.getQueryData<${componentName}Return>(use${componentName}Query.queryKey(params), filters);
421
-
422
- use${componentName}Query.prefetch = (params: ${componentName}Variables) =>
423
- queryClient.prefetchQuery<${componentName}Return>(use${componentName}Query.queryKey(params), ()=> use${componentName}Query.fetch(params));
424
-
425
- use${componentName}Query.cancelQueries = (params: ${componentName}Variables) => queryClient.cancelQueries(use${componentName}Query.queryKey(params))
426
- use${componentName}Query.invalidate = (params: ${componentName}Variables) =>
427
- queryClient.invalidateQueries<${componentName}Return>(use${componentName}Query.queryKey(params));
428
-
429
-
430
- use${componentName}Query.refetchStale = (params: ${componentName}Variables) =>
431
- queryClient.refetchQueries<${componentName}Return>(use${componentName}Query.queryKey(params), { stale: true });
432
-
433
- use${componentName}Query.refetchStale = (params: ${componentName}Variables) =>
434
- queryClient.refetchQueries<${componentName}Return>(use${componentName}Query.queryKey(params), { stale: true });
435
-
436
- type ${componentName}QueryProps<T = ${componentName}Return> = ${componentName}Variables & {
437
- options?: UseQueryOptions<${componentName}Return, AxiosError, T, any>
438
- }
439
- export function use${componentName}Query<T = ${componentName}Return>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
440
- return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
441
- { enabled: ${enabledParam}, ...options }
442
- );}
443
-
444
- type ${componentName}MutationProps<T> = {
445
- options?: UseMutationOptions<${componentName}Return, AxiosError, ${componentName}Variables, T>
446
- }
447
- export function use${componentName}Mutation<T = ${componentName}Return>(props?: ${componentName}MutationProps<T>) {
448
- return useMutation(async (data) => use${componentName}Query.fetch(data),
449
- props?.options
450
- )};`;
451
- }
452
- if (!requestBodyComponent && paramsInPath.length && queryParam && !headerParam) {
453
- output += `
454
- type ${componentName}Return = ${genericsTypes}
455
- type ${componentName}Variables = {
456
- ${paramsTypes}
457
- ${queryParamsType};
458
- }
459
-
460
- use${componentName}Query.fetch = async (props:${componentName}Variables) => {
461
- const {${paramsInPath.join(', ')}, ...queryParams} = props
462
- const params = queryString.stringify(queryParams);
463
- const result = await api.${verb}<${componentName}Return>(\`${route}?\${params}\`)
464
- return result.data;
465
- }
466
-
467
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
468
- use${componentName}Query.queryKey = (params: ${componentName}Variables ): QueryKey => [...use${componentName}Query.baseKey(), params];
469
-
470
- use${componentName}Query.updateCache = (
471
- {params, updater, options}:
472
- {params: ${componentName}Variables,
473
- updater: Updater<${componentName}Return | undefined, ${componentName}Return | undefined>,
474
- options?: SetDataOptions | undefined}
475
- ) => queryClient.setQueryData<${componentName}Return>(use${componentName}Query.queryKey(params), updater, options);
476
-
477
- use${componentName}Query.getQueryState = ({params, filters}:{params: ${componentName}Variables, filters?: QueryFilters})=> queryClient.getQueryState<${componentName}Return>(use${componentName}Query.queryKey(params), filters);
478
- use${componentName}Query.getQueryData = ({params, filters}:{params: ${componentName}Variables, filters?: QueryFilters})=> queryClient.getQueryData<${componentName}Return>(use${componentName}Query.queryKey(params), filters);
479
-
480
- use${componentName}Query.prefetch = (params: ${componentName}Variables) =>
481
- queryClient.prefetchQuery<${componentName}Return>(use${componentName}Query.queryKey(params), ()=> use${componentName}Query.fetch(params));
482
-
483
- use${componentName}Query.cancelQueries = (params: ${componentName}Variables) => queryClient.cancelQueries(use${componentName}Query.queryKey(params))
484
- use${componentName}Query.invalidate = (params: ${componentName}Variables) =>
485
- queryClient.invalidateQueries<${componentName}Return>(use${componentName}Query.queryKey(params));
486
-
487
- use${componentName}Query.refetchStale = (params: ${componentName}Variables) =>
488
- queryClient.refetchQueries<${componentName}Return>(use${componentName}Query.queryKey(params), { stale: true });
489
-
490
- type ${componentName}QueryProps<T = ${componentName}Return> = ${componentName}Variables & {
491
- options?: UseQueryOptions<${componentName}Return, AxiosError, T, any>
492
- }
493
- export function use${componentName}Query<T = ${componentName}Return>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
494
- return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
495
- { enabled: ${enabledParam}, ...options }
496
- );}
497
-
498
- type ${componentName}MutationProps<T> = {
499
- options?: UseMutationOptions<${componentName}Return, AxiosError, ${componentName}Variables, T>
500
- }
501
- export function use${componentName}Mutation<T = ${componentName}Return>(props?: ${componentName}MutationProps<T>) {
502
- return useMutation(async (data) => use${componentName}Query.fetch(data),
503
- props?.options
504
- )};`;
505
- }
506
- if (!requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
507
- output += `
508
- type ${componentName}Return = ${genericsTypes}
509
- use${componentName}Query.fetch = async () => {
510
- const result = await api.${verb}<${componentName}Return>(\`${route}\`);
511
- return result.data;
512
- }
513
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
514
- use${componentName}Query.queryKey = (): QueryKey => use${componentName}Query.baseKey()
515
-
516
- use${componentName}Query.updateCache = ({updater, options}:
517
- {updater: Updater<${componentName}Return | undefined, ${componentName}Return | undefined>,
518
- options?: SetDataOptions | undefined}
519
- ) => queryClient.setQueryData<${componentName}Return>(use${componentName}Query.queryKey(), updater, options);
520
-
521
- use${componentName}Query.getQueryState = (props?: {filters?: QueryFilters})=> queryClient.getQueryState<${componentName}Return>(use${componentName}Query.queryKey(), props?.filters);
522
- use${componentName}Query.getQueryData = (props?: {filters?: QueryFilters})=> queryClient.getQueryData<${componentName}Return>(use${componentName}Query.queryKey(), props?.filters);
523
-
524
- use${componentName}Query.prefetch = () =>
525
- queryClient.prefetchQuery<${componentName}Return>(use${componentName}Query.queryKey(), ()=> use${componentName}Query.fetch());
526
-
527
- use${componentName}Query.cancelQueries = () => queryClient.cancelQueries(use${componentName}Query.queryKey())
528
- use${componentName}Query.invalidate = () =>
529
- queryClient.invalidateQueries<${componentName}Return>(use${componentName}Query.queryKey());
530
-
531
- use${componentName}Query.refetchStale = () =>
532
- queryClient.refetchQueries<${componentName}Return>(use${componentName}Query.queryKey(), { stale: true });
533
-
534
- type ${componentName}QueryProps<T = ${componentName}Return> = {
535
- options?: UseQueryOptions<${componentName}Return, AxiosError, T, any>
536
- }
537
- export function use${componentName}Query<T = ${componentName}Return>(props?: ${componentName}QueryProps<T>) {
538
- return useQuery(use${componentName}Query.queryKey(), use${componentName}Query.fetch, props?.options
539
- );}
540
-
541
- type ${componentName}MutationProps<T> = {
542
- options?: UseMutationOptions<${componentName}Return, AxiosError, void, T>
543
- }
544
- export function use${componentName}Mutation<T = ${componentName}Return>(props?: ${componentName}MutationProps<T>) {
545
- return useMutation(async () => use${componentName}Query.fetch(),
546
- props?.options
547
- )};`;
548
- }
549
- if (!requestBodyComponent && !paramsInPath.length && queryParam && !headerParam) {
550
- output += `
551
-
552
- type ${componentName}Return = ${genericsTypes}
553
- type ${componentName}Variables = {
554
- ${queryParamsType}
555
- }
556
-
557
- use${componentName}Query.fetch = async (props: ${componentName}Variables) => {
558
- const params = queryString.stringify({${queryParams
559
- .map((param) => `"${param.name}": props["${param.name}"]`)
560
- .join(',')}});
561
- const result = await api.${verb}<${componentName}Return>(\`${route}?\${params}\`)
562
- return result.data;
563
- }
564
-
565
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
566
- use${componentName}Query.queryKey = (params: ${componentName}Variables ): QueryKey => [...use${componentName}Query.baseKey(), params];
567
-
568
- use${componentName}Query.updateCache = (
569
- {params, updater, options}:
570
- {params: ${componentName}Variables,
571
- updater: Updater<${componentName}Return | undefined, ${componentName}Return | undefined>,
572
- options?: SetDataOptions | undefined}
573
- ) => queryClient.setQueryData<${componentName}Return>(use${componentName}Query.queryKey(params), updater, options);
574
-
575
- use${componentName}Query.getQueryState = ({params, filters}:{params: ${componentName}Variables, filters?: QueryFilters})=> queryClient.getQueryState<${componentName}Return>(use${componentName}Query.queryKey(params), filters);
576
- use${componentName}Query.getQueryData = ({params, filters}:{params: ${componentName}Variables, filters?: QueryFilters})=> queryClient.getQueryData<${componentName}Return>(use${componentName}Query.queryKey(params), filters);
577
-
578
- use${componentName}Query.prefetch = (params: ${componentName}Variables) =>
579
- queryClient.prefetchQuery<${componentName}Return>(use${componentName}Query.queryKey(params), ()=> use${componentName}Query.fetch(params));
580
-
581
- use${componentName}Query.cancelQueries = (params: ${componentName}Variables) => queryClient.cancelQueries(use${componentName}Query.queryKey(params))
582
- use${componentName}Query.invalidate = (params: ${componentName}Variables) =>
583
- queryClient.invalidateQueries<${componentName}Return>(use${componentName}Query.queryKey(params));
584
-
585
- use${componentName}Query.refetchStale = (params: ${componentName}Variables) =>
586
- queryClient.refetchQueries<${componentName}Return>(use${componentName}Query.queryKey(params), { stale: true });
587
-
588
- export function use${componentName}Query<T = ${componentName}Return>({ options = {}, ...props }: ${componentName}Variables & { options?: UseQueryOptions<${componentName}Return, AxiosError, T, any>}) {
589
- return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
590
- { enabled: ${enabledParam}, ...options }
591
- );}
592
-
593
- export function use${componentName}Mutation<T = ${componentName}Return>(props?: { options?: UseMutationOptions<${componentName}Return, AxiosError, ${componentName}Variables, T>}) {
594
- return useMutation(async (data) => use${componentName}Query.fetch(data),
595
- props?.options
596
- )};
597
- `;
598
- }
599
- if (requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
600
- output += `
601
- type ${componentName}Return = ${genericsTypes}
602
- type ${componentName}Variables = ${requestBodyComponent};
603
-
604
- use${componentName}Query.fetch = async (body: ${componentName}Variables) => {
605
- const result = await api.${verb}<${componentName}Return>(\`${route}\`, body)
606
- return result.data
607
- }
608
-
609
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
610
- use${componentName}Query.queryKey = (params: ${componentName}Variables ): QueryKey => [...use${componentName}Query.baseKey(), params];
611
-
612
- use${componentName}Query.updateCache = (
613
- {params, updater, options}:
614
- {params: ${componentName}Variables,
615
- updater: Updater<${componentName}Return | undefined, ${componentName}Return | undefined>,
616
- options?: SetDataOptions | undefined}
617
- ) => queryClient.setQueryData<${componentName}Return>(use${componentName}Query.queryKey(params), updater, options);
618
-
619
- use${componentName}Query.getQueryState = ({params, filters}:{params: ${componentName}Variables, filters?: QueryFilters})=> queryClient.getQueryState<${componentName}Return>(use${componentName}Query.queryKey(params), filters);
620
- use${componentName}Query.getQueryData = ({params, filters}:{params: ${componentName}Variables, filters?: QueryFilters})=> queryClient.getQueryData<${componentName}Return>(use${componentName}Query.queryKey(params), filters);
621
-
622
- use${componentName}Query.prefetch = (params: ${componentName}Variables) =>
623
- queryClient.prefetchQuery<${componentName}Return>(use${componentName}Query.queryKey(params), ()=> use${componentName}Query.fetch(params));
624
-
625
- use${componentName}Query.cancelQueries = (params: ${componentName}Variables) => queryClient.cancelQueries(use${componentName}Query.queryKey(params))
626
- use${componentName}Query.invalidate = (params: ${componentName}Variables) =>
627
- queryClient.invalidateQueries<${componentName}Return>(use${componentName}Query.queryKey(params));
628
-
629
-
630
- use${componentName}Query.refetchStale = (params: ${componentName}Variables) =>
631
- queryClient.refetchQueries<${componentName}Return>(use${componentName}Query.queryKey(params), { stale: true });
632
-
633
-
634
- type ${componentName}QueryProps<T = ${componentName}Return> = ${componentName}Variables & {
635
- options?: UseQueryOptions<${componentName}Return, AxiosError, T, any>
636
- }
637
- export function use${componentName}Query<T = ${componentName}Return>({ options = {}, ...body }: ${componentName}QueryProps<T>) {
638
- return useQuery(use${componentName}Query.queryKey(body), async () => use${componentName}Query.fetch(body), options
639
- );}
640
-
641
- type ${componentName}MutationProps<T> = {
642
- options?: UseMutationOptions<${componentName}Return, AxiosError, ${componentName}Variables, T>
643
- }
644
- export function use${componentName}Mutation<T = ${componentName}Return>(props?: ${componentName}MutationProps<T>) {
645
- return useMutation(async (body) => use${componentName}Query.fetch(body),
646
- props?.options
647
- )};`;
648
- }
649
- if (requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
650
- output += `
651
- type ${componentName}Return = ${genericsTypes}
652
- type ${componentName}Variables = {
653
- body: ${requestBodyComponent}
654
- ${paramsTypes}
655
- }
656
-
657
- type ${componentName}QueryProps<T = ${componentName}Return> = ${componentName}Variables & {
658
- options?: UseQueryOptions<${componentName}Return, AxiosError, T, any>
659
- }
660
-
661
- use${componentName}Query.fetch = async (props: ${componentName}Variables) => {
662
- const {${paramsInPath.join(', ')}, ...body} = props
663
- const result = await api.${verb}<${componentName}Return>(\`${route}\`, body)
664
- return result.data
665
- }
666
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
667
- use${componentName}Query.queryKey = (params: ${componentName}Variables ): QueryKey => [...use${componentName}Query.baseKey(), params];
668
-
669
- use${componentName}Query.updateCache = (
670
- {params, updater, options}:
671
- {params: ${componentName}Variables,
672
- updater: Updater<${componentName}Return | undefined, ${componentName}Return | undefined>,
673
- options?: SetDataOptions | undefined}
674
- ) => queryClient.setQueryData<${componentName}Return>(use${componentName}Query.queryKey(params), updater, options);
675
-
676
- use${componentName}Query.getQueryState = ({params, filters}:{params: ${componentName}Variables, filters?: QueryFilters})=> queryClient.getQueryState<${componentName}Return>(use${componentName}Query.queryKey(params), filters);
677
- use${componentName}Query.getQueryData = ({params, filters}:{params: ${componentName}Variables, filters?: QueryFilters})=> queryClient.getQueryData<${componentName}Return>(use${componentName}Query.queryKey(params), filters);
678
-
679
- use${componentName}Query.prefetch = (params: ${componentName}Variables) =>
680
- queryClient.prefetchQuery<${componentName}Return>(use${componentName}Query.queryKey(params), ()=> use${componentName}Query.fetch(params));
681
-
682
- use${componentName}Query.cancelQueries = (params: ${componentName}Variables) => queryClient.cancelQueries(use${componentName}Query.queryKey(params))
683
- use${componentName}Query.invalidate = (params: ${componentName}Variables) =>
684
- queryClient.invalidateQueries<${componentName}Return>(use${componentName}Query.queryKey(params));
685
-
686
-
687
- use${componentName}Query.refetchStale = (params: ${componentName}Variables) =>
688
- queryClient.refetchQueries<${componentName}Return>(use${componentName}Query.queryKey(params), { stale: true });
689
-
690
-
691
- export function use${componentName}Query<T = ${componentName}Return>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
692
- return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
693
- { enabled: ${enabledParam}, ...options }
694
- );}
695
-
696
- type ${componentName}MutationProps<T> = {
697
- options?: UseMutationOptions<${componentName}Return, AxiosError, ${componentName}Variables, T>
698
- }
699
- export function use${componentName}Mutation<T = ${componentName}Return>(props?: ${componentName}MutationProps<T>) {
700
- return useMutation(async (body) => use${componentName}Query.fetch(body),
701
- props?.options
702
- )};`;
703
- }
704
- if (requestBodyComponent && !paramsInPath.length && queryParam && !headerParam) {
705
- output += `
706
- type ${componentName}Return = ${genericsTypes}
707
- type ${componentName}Variables = {
708
- body: ${requestBodyComponent}
709
- ${queryParamsType}
710
- }
711
-
712
- type ${componentName}QueryProps<T = ${componentName}Return> = ${componentName}Variables & {
713
- options?: UseQueryOptions<${componentName}Return, AxiosError, T, any>
714
- }
715
-
716
- use${componentName}Query.fetch = async (props: ${componentName}Variables) => {
717
- const params = queryString.stringify({
718
- ${queryParams.map((param) => `["${param.name}"]: props["${param.name}"]`).join(',')}
719
- });
720
- const result = await api.${verb}<${componentName}Return>(\`${route}?\${params}\`, props.body)
721
- return result.data
722
- }
723
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
724
- use${componentName}Query.queryKey = (params: ${componentName}Variables ): QueryKey => [...use${componentName}Query.baseKey(), params];
725
-
726
- use${componentName}Query.updateCache = (
727
- {params, updater, options}:
728
- {params: ${componentName}Variables,
729
- updater: Updater<${componentName}Return | undefined, ${componentName}Return | undefined>,
730
- options?: SetDataOptions | undefined}
731
- ) => queryClient.setQueryData<${componentName}Return>(use${componentName}Query.queryKey(params), updater, options);
732
-
733
- use${componentName}Query.getQueryState = ({params, filters}:{params: ${componentName}Variables, filters?: QueryFilters})=> queryClient.getQueryState<${componentName}Return>(use${componentName}Query.queryKey(params), filters);
734
- use${componentName}Query.getQueryData = ({params, filters}:{params: ${componentName}Variables, filters?: QueryFilters})=> queryClient.getQueryData<${componentName}Return>(use${componentName}Query.queryKey(params), filters);
735
-
736
- use${componentName}Query.prefetch = (params: ${componentName}Variables) =>
737
- queryClient.prefetchQuery<${componentName}Return>(use${componentName}Query.queryKey(params), ()=> use${componentName}Query.fetch(params));
738
-
739
- use${componentName}Query.cancelQueries = (params: ${componentName}Variables) => queryClient.cancelQueries(use${componentName}Query.queryKey(params))
740
- use${componentName}Query.invalidate = (params: ${componentName}Variables) =>
741
- queryClient.invalidateQueries<${componentName}Return>(use${componentName}Query.queryKey(params));
742
-
743
-
744
- use${componentName}Query.refetchStale = (params: ${componentName}Variables) =>
745
- queryClient.refetchQueries<${componentName}Return>(use${componentName}Query.queryKey(params), { stale: true });
746
-
747
-
748
- export function use${componentName}Query<T = ${componentName}Return>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
749
- return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
750
- { enabled: ${enabledParam}, ...options }
751
- );}
752
-
753
-
754
- type ${componentName}MutationProps<T> = {
755
- options?: UseMutationOptions<${componentName}Return, AxiosError, ${componentName}Variables, T>
756
- }
757
- export function use${componentName}Mutation<T = ${componentName}Return>(props?: ${componentName}MutationProps<T>) {
758
- return useMutation(async (body) => use${componentName}Query.fetch(body),
759
- props?.options
760
- )};`;
761
- }
762
- if (requestBodyComponent && paramsInPath.length && queryParam && !headerParam) {
763
- output += `// TODO: NOT SUPPORTED 2`;
764
- }
765
- if (requestBodyComponent && !paramsInPath.length && queryParam && headerParam) {
766
- output += `// TODO: NOT SUPPORTED 3`;
767
- }
768
- if (requestBodyComponent && paramsInPath.length && queryParam && headerParam) {
769
- output += `// TODO: NOT SUPPORTED 4`;
770
- }
771
- if (!requestBodyComponent && paramsInPath.length && !queryParam && headerParam) {
772
- output += `// TODO: NOT SUPPORTED 5`;
773
- }
774
- if (!requestBodyComponent && paramsInPath.length && queryParam && headerParam) {
775
- output += `// TODO: NOT SUPPORTED 6`;
776
- }
777
- if (!requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
778
- output += `
779
- type ${componentName}Return = ${genericsTypes}
780
- type ${componentName}Variables = {
781
- ${headerParam}
782
- };
783
-
784
- use${componentName}Query.fetch = async (headers: ${componentName}Variables) => {
785
- const result = await api.${verb}<${componentName}Return>(\`${route}\`, {headers: headers});
786
- return result.data;
787
- }
788
-
789
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
790
- use${componentName}Query.queryKey = (params: ${componentName}Variables ): QueryKey => [...use${componentName}Query.baseKey(), params];
791
-
792
- use${componentName}Query.updateCache = (
793
- {params, updater, options}:
794
- {params: ${componentName}Variables,
795
- updater: Updater<${componentName}Return | undefined, ${componentName}Return | undefined>,
796
- options?: SetDataOptions | undefined}
797
- ) => queryClient.setQueryData<${componentName}Return>(use${componentName}Query.queryKey(params), updater, options);
798
-
799
- use${componentName}Query.getQueryState = ({params, filters}:{params: ${componentName}Variables, filters?: QueryFilters})=> queryClient.getQueryState<${componentName}Return>(use${componentName}Query.queryKey(params), filters);
800
- use${componentName}Query.getQueryData = ({params, filters}:{params: ${componentName}Variables, filters?: QueryFilters})=> queryClient.getQueryData<${componentName}Return>(use${componentName}Query.queryKey(params), filters);
801
-
802
- use${componentName}Query.prefetch = (params: ${componentName}Variables) =>
803
- queryClient.prefetchQuery<${componentName}Return>(use${componentName}Query.queryKey(params), ()=> use${componentName}Query.fetch(params));
804
-
805
- use${componentName}Query.cancelQueries = (params: ${componentName}Variables) => queryClient.cancelQueries(use${componentName}Query.queryKey(params))
806
- use${componentName}Query.invalidate = (params: ${componentName}Variables) =>
807
- queryClient.invalidateQueries<${componentName}Return>(use${componentName}Query.queryKey(params));
808
-
809
-
810
- use${componentName}Query.refetchStale = (params: ${componentName}Variables) =>
811
- queryClient.refetchQueries<${componentName}Return>(use${componentName}Query.queryKey(params), { stale: true });
812
-
813
-
814
- type ${componentName}QueryProps<T = ${componentName}Return> = ${componentName}Variables & {
815
- options?: UseQueryOptions<${componentName}Return, AxiosError, T, any>
816
- }
817
- export function use${componentName}Query<T = ${componentName}Return>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
818
- return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
819
- { enabled: ${enabledParam}, ...options }
820
- );}
821
-
822
- type ${componentName}MutationProps<T> = {
823
- options?: UseMutationOptions<${componentName}Return, AxiosError, ${componentName}Variables, T>
824
- }
825
- export function use${componentName}Mutation<T = ${componentName}Return>(props?: ${componentName}MutationProps<T>) {
826
- return useMutation(async (data) => use${componentName}Query.fetch(data),
827
- props?.options
828
- )};`;
829
- }
830
- if (!requestBodyComponent && !paramsInPath.length && queryParam && headerParam) {
831
- output += `
832
- type ${componentName}Return = ${genericsTypes}
833
-
834
- type ${componentName}Variables = {
835
- ${headerParam}
836
- ${queryParamsType};
837
- };
838
-
839
- use${componentName}Query.fetch = async (data: ${componentName}Variables) => {
840
- const params = queryString.stringify({
841
- ${queryParams.map((p) => `"${p.name}": data["${p.name}"]`).join(',')}
842
- });
843
- const headers = {
844
- ${headerParams.map((p) => `"${p.name}": data["${p.name}"]`).join(',')}
845
- }
846
- const result = await api.${verb}<${componentName}Return>(\`${route}?\${params}\`, {headers})
847
- return result.data;
848
- }
849
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
850
- use${componentName}Query.queryKey = (params: ${componentName}Variables ): QueryKey => [...use${componentName}Query.baseKey(), params];
851
-
852
- use${componentName}Query.updateCache = (
853
- {params, updater, options}:
854
- {params: ${componentName}Variables,
855
- updater: Updater<${componentName}Return | undefined, ${componentName}Return | undefined>,
856
- options?: SetDataOptions | undefined}
857
- ) => queryClient.setQueryData<${componentName}Return>(use${componentName}Query.queryKey(params), updater, options);
858
-
859
- use${componentName}Query.getQueryState = ({params, filters}:{params: ${componentName}Variables, filters?: QueryFilters})=> queryClient.getQueryState<${componentName}Return>(use${componentName}Query.queryKey(params), filters);
860
- use${componentName}Query.getQueryData = ({params, filters}:{params: ${componentName}Variables, filters?: QueryFilters})=> queryClient.getQueryData<${componentName}Return>(use${componentName}Query.queryKey(params), filters);
861
-
862
- use${componentName}Query.prefetch = (params: ${componentName}Variables) =>
863
- queryClient.prefetchQuery<${componentName}Return>(use${componentName}Query.queryKey(params), ()=> use${componentName}Query.fetch(params));
864
-
865
- use${componentName}Query.cancelQueries = (params: ${componentName}Variables) => queryClient.cancelQueries(use${componentName}Query.queryKey(params))
866
- use${componentName}Query.invalidate = (params: ${componentName}Variables) =>
867
- queryClient.invalidateQueries<${componentName}Return>(use${componentName}Query.queryKey(params));
868
-
869
-
870
- use${componentName}Query.refetchStale = (params: ${componentName}Variables) =>
871
- queryClient.refetchQueries<${componentName}Return>(use${componentName}Query.queryKey(params), { stale: true });
872
-
873
- type ${componentName}QueryProps<T = ${componentName}Return> = ${componentName}Variables & {
874
- options?: UseQueryOptions<${componentName}Return, AxiosError, T, any>
875
- }
876
- export function use${componentName}Query<T = ${componentName}Return>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
877
- return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
878
- { enabled: ${enabledParam}, ...options }
879
- );}
880
-
881
- type ${componentName}MutationProps<T> = {
882
- options?: UseMutationOptions<${componentName}Return, AxiosError, ${componentName}Variables, T>
883
- }
884
-
885
- export function use${componentName}Mutation<T = ${componentName}Return>(props?: ${componentName}MutationProps<T>) {
886
- return useMutation(async (data) => use${componentName}Query.fetch(data),
887
- props?.options
888
- )};`;
889
- }
890
- if (requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
891
- output += `
892
- type ${componentName}Return = ${genericsTypes}
893
-
894
- type ${componentName}Variables = {
895
- body: ${requestBodyComponent}
896
- ${headerParam}
897
- };
898
-
899
- use${componentName}Query.fetch = async (body: ${componentName}Variables) => {
900
- const headers = {
901
- ${headerParams.map((param) => `"${param.name}": body["${param.name}"]`).join(',')}
902
- }
903
- const result = await api.${verb}<${componentName}Return>(\`${route}\`, body, {headers})
904
- return result.data
905
- }
906
-
907
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
908
- use${componentName}Query.queryKey = (params: ${componentName}Variables ): QueryKey => [...use${componentName}Query.baseKey(), params];
909
-
910
- use${componentName}Query.updateCache = (
911
- {params, updater, options}:
912
- {params: ${componentName}Variables,
913
- updater: Updater<${componentName}Return | undefined, ${componentName}Return | undefined>,
914
- options?: SetDataOptions | undefined}
915
- ) => queryClient.setQueryData<${componentName}Return>(use${componentName}Query.queryKey(params), updater, options);
916
-
917
- use${componentName}Query.getQueryState = ({params, filters}:{params: ${componentName}Variables, filters?: QueryFilters})=> queryClient.getQueryState<${componentName}Return>(use${componentName}Query.queryKey(params), filters);
918
- use${componentName}Query.getQueryData = ({params, filters}:{params: ${componentName}Variables, filters?: QueryFilters})=> queryClient.getQueryData<${componentName}Return>(use${componentName}Query.queryKey(params), filters);
919
-
920
- use${componentName}Query.prefetch = (params: ${componentName}Variables) =>
921
- queryClient.prefetchQuery<${componentName}Return>(use${componentName}Query.queryKey(params), ()=> use${componentName}Query.fetch(params));
922
-
923
- use${componentName}Query.cancelQueries = (params: ${componentName}Variables) => queryClient.cancelQueries(use${componentName}Query.queryKey(params))
924
- use${componentName}Query.invalidate = (params: ${componentName}Variables) =>
925
- queryClient.invalidateQueries<${componentName}Return>(use${componentName}Query.queryKey(params));
926
-
927
-
928
- use${componentName}Query.refetchStale = (params: ${componentName}Variables) =>
929
- queryClient.refetchQueries<${componentName}Return>(use${componentName}Query.queryKey(params), { stale: true });
930
-
931
- type ${componentName}QueryProps<T = ${componentName}Return> = ${componentName}Variables & {
932
- options?: UseQueryOptions<${componentName}Return, AxiosError, T, any>
933
- }
934
- export function use${componentName}Query<T = ${componentName}Return>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
935
- return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
936
- { enabled: ${enabledParam}, ...options }
937
- );}
938
-
939
-
940
- type ${componentName}MutationProps<T> = {
941
- options?: UseMutationOptions<${componentName}Return, AxiosError, ${componentName}Variables, T>
942
- }
943
- export function use${componentName}Mutation<T = ${componentName}Return>(props?: ${componentName}MutationProps<T>) {
944
- return useMutation(async (body) => use${componentName}Query.fetch(body),
945
- props?.options
946
- )};`;
947
- }
948
- if (requestBodyComponent && paramsInPath.length && !queryParam && headerParam) {
949
- output += `// TODO: CODEGEN DOES NOT SUPPORT requestBodyComponent AND paramsInPath AND headerParam`;
950
- }
951
- return output;
952
- };
953
- const generateQueryHooks = (spec, operationIds, headerFilters) => {
954
- const { paths, components } = spec;
955
- let output = '';
956
- Object.entries(paths).forEach(([route, verbs]) => {
957
- Object.entries(verbs).forEach(([verb, operation]) => {
958
- if (['get', 'post', 'patch', 'put', 'delete'].includes(verb) && !operation.deprecated) {
959
- output += generateRestfulComponent({
960
- operation,
961
- verb,
962
- route: spec.basePath + route,
963
- operationIds,
964
- parameters: verbs.parameters,
965
- schemasComponents: components,
966
- headerFilters,
967
- });
968
- }
969
- });
970
- });
971
- return output;
972
- };
973
- /**
974
- * Main entry of the generator. Generate react-query component from openAPI.
975
- */
976
- export const importOpenApi = async ({ data, format, apiDirectory, queryClientDir, headerFilters = [], }) => {
977
- const operationIds = [];
978
- let specs = await importSpecs(data, format);
979
- resolveDiscriminator(specs);
980
- let output = '';
981
- output = `
982
- import {
983
- useQuery,
984
- useMutation,
985
- UseQueryOptions,
986
- UseMutationOptions,
987
- QueryKey,
988
- SetDataOptions,
989
- QueryFilters
990
- } from '@tanstack/react-query';
991
-
992
- import queryString from 'query-string';
993
- import { AxiosError } from 'axios';
994
- import { api } from '${apiDirectory}';
995
- import { queryClient } from '${queryClientDir}';
996
-
997
- type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput);
998
-
999
- // SCEHMAS
1000
- ${generateSchemasDefinition(specs.components?.schemas)}
1001
-
1002
- // RESPONSES
1003
- ${generateResponsesDefinition(specs.components?.responses)}
1004
-
1005
- // REQUEST BODIES
1006
- ${generateRequestBodiesDefinition(specs.components?.requestBodies)}
1007
-
1008
- // HOOKS
1009
- ${generateQueryHooks(specs, operationIds, headerFilters)}
1010
- `;
1011
- return output;
1012
- };