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