react-query-lightbase-codegen 0.0.2 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,739 +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
-
8
- import {
9
- ComponentsObject,
10
- OpenAPIObject,
11
- OperationObject,
12
- ParameterObject,
13
- PathItemObject,
14
- ReferenceObject,
15
- RequestBodyObject,
16
- ResponseObject,
17
- SchemaObject,
18
- } from 'openapi3-ts';
19
-
20
- import swagger2openapi from 'swagger2openapi';
21
-
22
- const yaml = require('js-yaml');
23
-
24
- const IdentifierRegexp = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
25
-
26
- /**
27
- * Import and parse the openapi spec from a yaml/json
28
- */
29
- const importSpecs = (data: string, extension: 'yaml' | 'json'): Promise<OpenAPIObject> => {
30
- const schema = extension === 'yaml' ? yaml.load(data) : JSON.parse(data);
31
- return new Promise((resolve, reject) => {
32
- if (!schema.openapi || !schema.openapi.startsWith('3.')) {
33
- swagger2openapi.convertObj(schema, {}, (err, convertedObj) => {
34
- if (err) {
35
- reject(err);
36
- } else {
37
- resolve(convertedObj.openapi);
38
- }
39
- });
40
- } else {
41
- resolve(schema);
42
- }
43
- });
44
- };
45
-
46
- /**
47
- * Discriminator helper for `ReferenceObject`
48
- */
49
- export const isReference = (property: any): property is ReferenceObject => {
50
- return Boolean(property.$ref);
51
- };
52
-
53
- /**
54
- * Return the typescript equivalent of open-api data type
55
- */
56
- export const getScalar = (item: SchemaObject) => {
57
- const nullable = item.nullable ? ' | null' : '';
58
-
59
- switch (item.type) {
60
- case 'number':
61
- case 'integer':
62
- return 'number' + nullable;
63
-
64
- case 'boolean':
65
- return 'boolean' + nullable;
66
-
67
- case 'array':
68
- return getArray(item) + nullable;
69
-
70
- case 'string':
71
- return (item.enum ? `"${item.enum.join(`" | "`)}"` : 'string') + nullable;
72
-
73
- case 'object':
74
- default:
75
- return getObject(item) + nullable;
76
- }
77
- };
78
-
79
- /**
80
- * Return the output type from the $ref
81
- */
82
- export const getRef = ($ref: ReferenceObject['$ref']) => {
83
- if ($ref.startsWith('#/components/schemas')) {
84
- return pascal($ref.replace('#/components/schemas/', ''));
85
- } else if ($ref.startsWith('#/components/responses')) {
86
- return pascal($ref.replace('#/components/responses/', '')) + 'Response';
87
- } else if ($ref.startsWith('#/components/parameters')) {
88
- return pascal($ref.replace('#/components/parameters/', '')) + 'Parameter';
89
- } else if ($ref.startsWith('#/components/requestBodies')) {
90
- return pascal($ref.replace('#/components/requestBodies/', '')) + 'RequestBody';
91
- } else {
92
- throw new Error('This library only resolve $ref that are include into `#/components/*` for now');
93
- }
94
- };
95
-
96
- /**
97
- * Return the output type from an array
98
- */
99
- export const getArray = (item: SchemaObject): string => {
100
- if (item.items) {
101
- if (!isReference(item.items) && (item.items.oneOf || item.items.allOf || item.items.enum)) {
102
- return `(${resolveValue(item.items)})[]`;
103
- } else {
104
- return `${resolveValue(item.items)}[]`;
105
- }
106
- } else {
107
- throw new Error('All arrays must have an `items` key define');
108
- }
109
- };
110
-
111
- /**
112
- * Return the output type from an object
113
- */
114
- export const getObject = (item: SchemaObject): string => {
115
- if (isReference(item)) {
116
- return getRef(item.$ref);
117
- }
118
-
119
- if (item.allOf) {
120
- return item.allOf.map(resolveValue).join(' & ');
121
- }
122
-
123
- if (item.oneOf) {
124
- return item.oneOf.map(resolveValue).join(' | ');
125
- }
126
-
127
- if (!item.type && !item.properties && !item.additionalProperties) {
128
- return '{}';
129
- }
130
-
131
- // Free form object (https://swagger.io/docs/specification/data-models/data-types/#free-form)
132
- if (
133
- item.type === 'object' &&
134
- !item.properties &&
135
- (!item.additionalProperties || item.additionalProperties === true || isEmpty(item.additionalProperties))
136
- ) {
137
- return '{[key: string]: any}';
138
- }
139
-
140
- // Consolidation of item.properties & item.additionalProperties
141
- let output = '{\n';
142
- if (item.properties) {
143
- output += Object.entries(item.properties)
144
- .map(([key, prop]: [string, ReferenceObject | SchemaObject]) => {
145
- const doc = isReference(prop) ? '' : formatDescription(prop.description, 2);
146
- const isRequired = (item.required || []).includes(key);
147
- const processedKey = IdentifierRegexp.test(key) ? key : `"${key}"`;
148
- return ` ${doc}${processedKey}${isRequired ? '' : '?'}: ${resolveValue(prop)};`;
149
- })
150
- .join('\n');
151
- }
152
-
153
- if (item.additionalProperties) {
154
- if (item.properties) {
155
- output += '\n';
156
- }
157
- output += ` [key: string]: ${
158
- item.additionalProperties === true ? 'any' : resolveValue(item.additionalProperties)
159
- };`;
160
- }
161
-
162
- if (item.properties || item.additionalProperties) {
163
- if (output === '{\n') {
164
- return '{}';
165
- }
166
- return output + '\n}';
167
- }
168
-
169
- return item.type === 'object' ? '{[key: string]: any}' : 'any';
170
- };
171
-
172
- /**
173
- * Resolve the value of a schema object to a proper type definition.
174
- */
175
- export const resolveValue = (schema: SchemaObject) =>
176
- isReference(schema) ? getRef(schema.$ref) : getScalar(schema);
177
-
178
- /**
179
- * Extract responses / request types from open-api specs
180
- */
181
- export const getResReqTypes = (
182
- responsesOrRequests: Array<[string, ResponseObject | ReferenceObject | RequestBodyObject]>
183
- ) =>
184
- uniq(
185
- responsesOrRequests.map(([_, res]) => {
186
- if (!res) {
187
- return 'void';
188
- }
189
-
190
- if (isReference(res)) {
191
- return getRef(res.$ref);
192
- }
193
-
194
- if (res.content) {
195
- for (let contentType of Object.keys(res.content)) {
196
- if (
197
- contentType.startsWith('application/json') ||
198
- contentType.startsWith('application/octet-stream')
199
- ) {
200
- const schema = res.content[contentType].schema!;
201
- return resolveValue(schema);
202
- }
203
- }
204
- return 'void';
205
- }
206
-
207
- return 'void';
208
- })
209
- ).join(' | ');
210
-
211
- /**
212
- * Return every params in a path
213
- *
214
- * @example
215
- * ```
216
- * getParamsInPath("/pet/{category}/{name}/");
217
- * // => ["category", "name"]
218
- * ```
219
- */
220
- export const getParamsInPath = (path: string) => {
221
- let n;
222
- const output = [];
223
- const templatePathRegex = /\{(\w+)}/g;
224
- while ((n = templatePathRegex.exec(path)) !== null) {
225
- output.push(n[1]);
226
- }
227
-
228
- return output;
229
- };
230
-
231
- /**
232
- * Generate the interface string
233
- */
234
- export const generateInterface = (name: string, schema: SchemaObject) => {
235
- const scalar = getScalar(schema);
236
- return `${formatDescription(schema.description)}export interface ${pascal(name)} ${scalar}`;
237
- };
238
-
239
- /**
240
- * Propagate every `discriminator.propertyName` mapping to the original ref
241
- *
242
- * Note: This method directly mutate the `specs` object.
243
- */
244
- export const resolveDiscriminator = (specs: OpenAPIObject) => {
245
- if (specs.components && specs.components.schemas) {
246
- Object.values(specs.components.schemas).forEach((schema) => {
247
- if (isReference(schema) || !schema.discriminator || !schema.discriminator.mapping) {
248
- return;
249
- }
250
- const { mapping, propertyName } = schema.discriminator;
251
-
252
- Object.entries(mapping).forEach(([name, ref]) => {
253
- if (!ref.startsWith('#/components/schemas/')) {
254
- throw new Error('Discriminator mapping outside of `#/components/schemas` is not supported');
255
- }
256
- set(
257
- specs,
258
- `components.schemas.${ref.slice('#/components/schemas/'.length)}.properties.${propertyName}.enum`,
259
- [name]
260
- );
261
- });
262
- });
263
- }
264
- };
265
-
266
- /**
267
- * Extract all types from #/components/schemas
268
- */
269
- export const generateSchemasDefinition = (schemas: ComponentsObject['schemas'] = {}) => {
270
- if (isEmpty(schemas)) {
271
- return '';
272
- }
273
-
274
- return (
275
- Object.entries(schemas)
276
- .map(([name, schema]) =>
277
- !isReference(schema) &&
278
- (!schema.type || schema.type === 'object') &&
279
- !schema.allOf &&
280
- !schema.oneOf &&
281
- !isReference(schema) &&
282
- !schema.nullable
283
- ? generateInterface(name, schema)
284
- : `${formatDescription(isReference(schema) ? undefined : schema.description)}export type ${pascal(
285
- name
286
- )} = ${resolveValue(schema)};`
287
- )
288
- .join('\n\n') + '\n'
289
- );
290
- };
291
-
292
- /**
293
- * Extract all types from #/components/requestBodies
294
- */
295
- export const generateRequestBodiesDefinition = (requestBodies: ComponentsObject['requestBodies'] = {}) => {
296
- if (isEmpty(requestBodies)) {
297
- return '';
298
- }
299
-
300
- return (
301
- '\n' +
302
- Object.entries(requestBodies)
303
- .map(([name, requestBody]) => {
304
- const doc = isReference(requestBody) ? '' : formatDescription(requestBody.description);
305
- const type = getResReqTypes([['', requestBody]]);
306
- const isEmptyInterface = type === '{}';
307
- if (isEmptyInterface) {
308
- return `export interface ${pascal(name)}RequestBody ${type}`;
309
- } else if (type.includes('{') && !type.includes('|') && !type.includes('&')) {
310
- return `${doc}export interface ${pascal(name)}RequestBody ${type}`;
311
- } else {
312
- return `${doc}export type ${pascal(name)}RequestBody = ${type};`;
313
- }
314
- })
315
- .join('\n\n') +
316
- '\n'
317
- );
318
- };
319
-
320
- /**
321
- * Extract all types from #/components/responses
322
- */
323
- export const generateResponsesDefinition = (responses: ComponentsObject['responses'] = {}) => {
324
- if (isEmpty(responses)) {
325
- return '';
326
- }
327
-
328
- return (
329
- '\n' +
330
- Object.entries(responses)
331
- .map(([name, response]) => {
332
- const doc = isReference(response) ? '' : formatDescription(response.description);
333
- const type = getResReqTypes([['', response]]);
334
- const isEmptyInterface = type === '{}';
335
- if (isEmptyInterface) {
336
- return `export interface RQ${pascal(name)}Response ${type}`;
337
- } else if (type.includes('{') && !type.includes('|') && !type.includes('&')) {
338
- return `${doc}export interface RQ${pascal(name)}Response ${type}`;
339
- } else {
340
- return `${doc}export type RQ${pascal(name)}Response = ${type};`;
341
- }
342
- })
343
- .join('\n\n') +
344
- '\n'
345
- );
346
- };
347
-
348
- /**
349
- * Format a description to code documentation.
350
- */
351
- export const formatDescription = (description?: string, tabSize = 0) =>
352
- description
353
- ? `/**\n${description
354
- .split('\n')
355
- .map((i) => `${' '.repeat(tabSize)} * ${i}`)
356
- .join('\n')}\n${' '.repeat(tabSize)} */\n${' '.repeat(tabSize)}`
357
- : '';
358
-
359
- /**
360
- * Generate a react-query component from openapi operation specs
361
- */
362
- export const generateRestfulComponent = (
363
- operation: OperationObject,
364
- verb: string,
365
- route: string,
366
- operationIds: string[],
367
- parameters: Array<ReferenceObject | ParameterObject> = [],
368
- schemasComponents?: ComponentsObject
369
- ) => {
370
- if (!operation.operationId) {
371
- throw new Error(`Every path must have a operationId - No operationId set for ${verb} ${route}`);
372
- }
373
- if (operationIds.includes(operation.operationId)) {
374
- throw new Error(`"${operation.operationId}" is duplicated in your schema definition!`);
375
- }
376
- operationIds.push(operation.operationId);
377
-
378
- route = route.replace(/\{/g, '${'); // `/pet/{id}` => `/pet/${id}`
379
-
380
- // Remove the last param of the route if we are in the DELETE case
381
- let lastParamInTheRoute: string | null = null;
382
-
383
- const componentName = pascal(operation.operationId!);
384
-
385
- const isOk = ([statusCode]: [string, ResponseObject | ReferenceObject]) =>
386
- statusCode.toString().startsWith('2');
387
-
388
- const responseTypes = getResReqTypes(Object.entries(operation.responses).filter(isOk)) || 'void';
389
- const requestBodyTypes = getResReqTypes([['body', operation.requestBody!]]);
390
- const needAResponseComponent = true;
391
-
392
- const paramsInPath = getParamsInPath(route).filter(
393
- (param) => !(verb === 'delete' && param === lastParamInTheRoute)
394
- );
395
- const { query: queryParams = [], path: pathParams = [] } = groupBy(
396
- [...parameters, ...(operation.parameters || [])].map<ParameterObject>((p) => {
397
- if (isReference(p)) {
398
- return get(schemasComponents, p.$ref.replace('#/components/', '').replace('/', '.'));
399
- } else {
400
- return p;
401
- }
402
- }),
403
- 'in'
404
- );
405
-
406
- const paramsTypes = paramsInPath
407
- .map((p) => {
408
- try {
409
- const { name, required, schema } = pathParams.find((i) => i.name === p)!;
410
- return `${name}${required ? '' : '?'}: ${resolveValue(schema!)}`;
411
- } catch (err) {
412
- throw new Error(`The path params ${p} can't be found in parameters (${operation.operationId})`);
413
- }
414
- })
415
- .join('; ');
416
-
417
- const queryParamsType = queryParams
418
- .map((p) => {
419
- const processedName = IdentifierRegexp.test(p.name) ? p.name : `"${p.name}"`;
420
- return `${formatDescription(p.description, 2)}${processedName}${p.required ? '' : '?'}: ${resolveValue(
421
- p.schema!
422
- )}`;
423
- })
424
- .join(';\n ');
425
-
426
- // Retrieve the type of the param for delete verb
427
- const lastParamInTheRouteDefinition =
428
- operation.parameters && lastParamInTheRoute
429
- ? (operation.parameters.find((p) => {
430
- if (isReference(p)) {
431
- return false;
432
- }
433
- return p.name === lastParamInTheRoute;
434
- }) as ParameterObject | undefined) // Reference is not possible
435
- : { schema: { type: 'string' } };
436
-
437
- if (!lastParamInTheRouteDefinition) {
438
- throw new Error(
439
- `The path params ${lastParamInTheRoute} can't be found in parameters (${operation.operationId})`
440
- );
441
- }
442
-
443
- let genericsTypes = `${needAResponseComponent ? componentName + 'Res' : responseTypes}`;
444
- if (verb !== 'get') {
445
- genericsTypes = `${needAResponseComponent ? componentName + 'Res' : responseTypes}`;
446
- }
447
-
448
- const description = formatDescription(
449
- operation.summary && operation.description
450
- ? `${operation.summary}\n\n${operation.description}`
451
- : `${operation.summary || ''}${operation.description || ''}`
452
- );
453
-
454
- let output = `\n\n${description}`;
455
-
456
- const typeOrInterface = `type ${componentName}Res =`;
457
-
458
- output += `
459
- ${needAResponseComponent ? `export ${typeOrInterface} ${responseTypes}` : ''}
460
- `;
461
-
462
- const queryParam = queryParamsType && queryParamsType !== 'void' ? `${queryParamsType}` : '';
463
- const requestBodyComponent = requestBodyTypes && requestBodyTypes !== 'void' ? `${requestBodyTypes}` : '';
464
-
465
- // QUERIES
466
- if (!requestBodyComponent && paramsInPath.length && !queryParam) {
467
- output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
468
- ${paramsTypes};
469
- options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
470
- }
471
- export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
472
- return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
473
- { enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
474
- );}
475
-
476
- use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'> ) => {
477
- const result = await api.${verb}<${genericsTypes}>(\`${route.replace(/\{/g, '{props.')}\`);
478
- return result.data;
479
- }
480
-
481
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
482
-
483
- use${componentName}Query.queryKey = (params: {${paramsTypes}} ): QueryKey => [...use${componentName}Query.baseKey(), params];
484
-
485
- `;
486
-
487
- output += `interface ${componentName}MutationVariables {
488
- ${paramsTypes}
489
- }
490
- interface ${componentName}MutationProps<T> {
491
- options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
492
- }
493
- export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
494
- return useMutation(async ({${paramsInPath.join(', ')}}) => {
495
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`)
496
- return result.data
497
- },
498
- props?.options
499
- )};`;
500
- }
501
-
502
- if (!requestBodyComponent && paramsInPath.length && queryParam) {
503
- output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
504
- ${paramsTypes};
505
- ${queryParamsType};
506
- options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
507
- }
508
- export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
509
- return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props), { enabled: !!props.${paramsInPath.join(
510
- ' && !!props.'
511
- )}, ...options }
512
- );}
513
-
514
- use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'>) => {
515
- const {${paramsInPath.join(', ')}, ...queryParams} = props
516
- const params = queryString.stringify(queryParams);
517
- const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
518
- return result.data;
519
- }
520
-
521
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
522
-
523
- use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'>): QueryKey => [...use${componentName}Query.baseKey(), params];
524
-
525
- `;
526
-
527
- output += `interface ${componentName}MutationVariables {
528
- ${paramsTypes}
529
- ${queryParamsType}
530
- }
531
- interface ${componentName}MutationProps<T> {
532
- options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
533
- }
534
- export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
535
- return useMutation(async (data) => {
536
- const {${paramsInPath.join(', ')}, ...queryParams} = data
537
- const params = queryString.stringify(queryParams);
538
- const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
539
- return result.data
540
- },
541
- props?.options
542
- )};`;
543
- }
544
-
545
- if (!requestBodyComponent && !paramsInPath.length && !queryParam) {
546
- output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
547
- options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
548
- }
549
- export function use${componentName}Query<T = ${genericsTypes}>(props?: ${componentName}QueryProps<T>) {
550
- return useQuery(use${componentName}Query.queryKey(), use${componentName}Query.fetch, props?.options
551
- );}
552
-
553
- use${componentName}Query.fetch = async () => {
554
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`);
555
- return result.data;
556
- }
557
-
558
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
559
-
560
- use${componentName}Query.queryKey = (): QueryKey => use${componentName}Query.baseKey()
561
-
562
- `;
563
-
564
- output += `interface ${componentName}MutationProps<T> {
565
- options?: UseMutationOptions<${genericsTypes}, AxiosError, void, T>
566
- }
567
- export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
568
- return useMutation(async () => {
569
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`);
570
- return result.data;
571
- },
572
- props?.options
573
- )};`;
574
- }
575
-
576
- if (!requestBodyComponent && !paramsInPath.length && queryParam) {
577
- output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
578
- ${queryParamsType};
579
- options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
580
- }
581
- export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
582
- return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
583
- { enabled: !!props.${queryParams.map((param) => param.name).join(' && !!props.')}, ...options }
584
- );}
585
-
586
- use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'>) => {
587
- const params = queryString.stringify({${queryParams
588
- .map((param) => `${param.name}: props.${param.name}`)
589
- .join(',')}});
590
- const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
591
- return result.data;
592
- }
593
-
594
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
595
-
596
- use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
597
-
598
- `;
599
-
600
- output += `interface ${componentName}MutationVariables {
601
- ${queryParamsType}
602
- }
603
- interface ${componentName}MutationProps<T> {
604
- options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
605
- }
606
-
607
- export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
608
- return useMutation(async (data) => {
609
- const params = queryString.stringify({${queryParams
610
- .map((param) => `${param.name}: data.${param.name}`)
611
- .join(',')}});
612
- const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
613
- return result.data;
614
- },
615
- props?.options
616
- )};`;
617
- }
618
-
619
- if (requestBodyComponent && !paramsInPath.length && !queryParam) {
620
- output += `type ${componentName}QueryVariables = ${requestBodyComponent};
621
- interface ${componentName}QueryProps<T = ${genericsTypes}> extends ${componentName}QueryVariables {
622
- options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
623
- }
624
- export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...body }: ${componentName}QueryProps<T>) {
625
- return useQuery(use${componentName}Query.queryKey(body), async () => use${componentName}Query.fetch(body), options
626
- );}
627
-
628
- use${componentName}Query.fetch = async (body: Omit<${componentName}QueryProps, 'options'>) => {
629
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
630
- return result.data
631
- }
632
-
633
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
634
-
635
- use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
636
-
637
- `;
638
-
639
- output += `type ${componentName}MutationVariables = ${requestBodyComponent};
640
- interface ${componentName}MutationProps<T> {
641
- options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
642
- }
643
- export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
644
- return useMutation(async (body) => {
645
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
646
- return result.data
647
- },
648
- props?.options
649
- )};`;
650
- }
651
-
652
- if (requestBodyComponent && paramsInPath.length && !queryParam) {
653
- output += `interface ${componentName}QueryProps<T = ${genericsTypes}> extends ${requestBodyComponent
654
- .replace('{', '')
655
- .replace('}', '')} {
656
- ${paramsTypes};
657
- options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
658
- }
659
- export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
660
- return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props), { enabled: !!props.${paramsInPath.join(
661
- ' && !!props.'
662
- )}, ...options }
663
- );}
664
-
665
- // HEHEH
666
- use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'>) => {
667
- const {${paramsInPath.join(', ')}, ...body} = props
668
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
669
- return result.data
670
- }
671
-
672
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
673
-
674
- use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
675
-
676
-
677
- `;
678
-
679
- output += `type ${componentName}MutationVariables = {${paramsTypes}} & ${requestBodyComponent}
680
- interface ${componentName}MutationProps<T> {
681
- options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
682
- }
683
- export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
684
- return useMutation(async (body) => use${componentName}Query.fetch(body),
685
- props?.options
686
- )};`;
687
- }
688
-
689
- if (requestBodyComponent && queryParam) {
690
- output += `// TODO: CODEGEN DOES NOT SUPPORT QUERYPARAM AND REQUESTBODY`;
691
- }
692
-
693
- return output;
694
- };
695
-
696
- /**
697
- * Main entry of the generator. Generate react-query component from openAPI.
698
- */
699
- const importOpenApi = async ({ data, format }: { data: string; format: 'yaml' | 'json' }) => {
700
- const operationIds: string[] = [];
701
- let specs = await importSpecs(data, format);
702
- resolveDiscriminator(specs);
703
-
704
- let output = `
705
- import { useQuery, useMutation, UseQueryOptions, UseMutationOptions, QueryKey } from 'react-query';
706
- import queryString from 'query-string';
707
- import {AxiosError} from 'axios';
708
- import { api } from 'api';
709
- `;
710
-
711
- output += '\n\n// SCEHMAS\n';
712
- output += generateSchemasDefinition(specs.components && specs.components.schemas);
713
-
714
- output += '\n\n// RESPONSES\n';
715
- output += generateResponsesDefinition(specs.components && specs.components.responses);
716
-
717
- output += '\n\n// REQUEST BODIES\n';
718
- output += generateRequestBodiesDefinition(specs.components && specs.components.requestBodies);
719
-
720
- output += '\n\n// HOOKS\n';
721
- Object.entries(specs.paths).forEach(([route, verbs]: [string, PathItemObject]) => {
722
- Object.entries(verbs).forEach(([verb, operation]: [string, OperationObject]) => {
723
- if (['get', 'post', 'patch', 'put', 'delete'].includes(verb) && !operation.deprecated) {
724
- output += generateRestfulComponent(
725
- operation,
726
- verb,
727
- route,
728
- operationIds,
729
- verbs.parameters,
730
- specs.components
731
- );
732
- }
733
- });
734
- });
735
-
736
- return output;
737
- };
738
-
739
- export default importOpenApi;