react-query-lightbase-codegen 0.0.11 → 0.0.14

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.
@@ -306,13 +306,13 @@ const formatDescription = (description, tabSize = 0) => description
306
306
  ? `/**\n${description
307
307
  .split('\n')
308
308
  .map((i) => `${' '.repeat(tabSize)} * ${i}`)
309
- .join('\n')}\n${' '.repeat(tabSize)} */\n${' '.repeat(tabSize)}`
309
+ .join('\n')}\n${' '.repeat(tabSize)} */${' '.repeat(tabSize)}`
310
310
  : '';
311
311
  exports.formatDescription = formatDescription;
312
312
  /**
313
313
  * Generate a react-query component from openapi operation specs
314
314
  */
315
- const generateRestfulComponent = (operation, verb, route, operationIds, parameters = [], schemasComponents) => {
315
+ const generateRestfulComponent = ({ operation, verb, route, operationIds, parameters, schemasComponents, headerFilters, }) => {
316
316
  const { operationId = route.replace('/', '') } = operation;
317
317
  if (operationId === '*') {
318
318
  throw new Error(`Invalid operationId/Route set for ${verb} ${route}`);
@@ -330,7 +330,7 @@ const generateRestfulComponent = (operation, verb, route, operationIds, paramete
330
330
  const requestBodyTypes = (0, exports.getResReqTypes)([['body', operation.requestBody]]);
331
331
  const needAResponseComponent = true;
332
332
  const paramsInPath = (0, exports.getParamsInPath)(route).filter((param) => !(verb === 'delete' && param === lastParamInTheRoute));
333
- const { query: queryParams = [], path: pathParams = [], header: headerParams = [] } = (0, groupBy_1.default)([...parameters, ...(operation.parameters || [])].map((p) => {
333
+ const { query: queryParams = [], path: pathParams = [], header = [], } = (0, groupBy_1.default)([...(parameters || []), ...(operation.parameters || [])].map((p) => {
334
334
  if ((0, exports.isReference)(p)) {
335
335
  return (0, get_1.default)(schemasComponents, p.$ref.replace('#/components/', '').replace('/', '.'));
336
336
  }
@@ -338,6 +338,7 @@ const generateRestfulComponent = (operation, verb, route, operationIds, paramete
338
338
  return p;
339
339
  }
340
340
  }), 'in');
341
+ const headerParams = header.filter((p) => !headerFilters?.includes(p.name));
341
342
  const paramsTypes = paramsInPath
342
343
  .map((p) => {
343
344
  try {
@@ -393,52 +394,43 @@ const generateRestfulComponent = (operation, verb, route, operationIds, paramete
393
394
  const headerParam = headerType && headerType !== 'void' ? `${headerType};` : '';
394
395
  const queryParam = queryParamsType && queryParamsType !== 'void' ? `${queryParamsType}` : '';
395
396
  const requestBodyComponent = requestBodyTypes && requestBodyTypes !== 'void' ? `${requestBodyTypes}` : '';
396
- console.log(headerParam);
397
397
  // QUERIES
398
398
  if (!requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
399
- output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
400
- ${paramsTypes};
401
- options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
399
+ output += `
400
+ type ${componentName}Variables = {
401
+ ${paramsTypes}
402
402
  }
403
- export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
404
- return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
405
- { enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
406
- );}
407
403
 
408
404
  use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'> ) => {
409
405
  const result = await api.${verb}<${genericsTypes}>(\`${route.replace(/\{/g, '{props.')}\`);
410
406
  return result.data;
411
407
  }
412
-
413
408
  use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
409
+ use${componentName}Query.queryKey = (params: ${componentName}Variables ): QueryKey => [...use${componentName}Query.baseKey(), params];
414
410
 
415
- use${componentName}Query.queryKey = (params: {${paramsTypes}} ): QueryKey => [...use${componentName}Query.baseKey(), params];
416
-
417
- `;
418
- output += `interface ${componentName}MutationVariables {
419
- ${paramsTypes}
411
+ type ${componentName}QueryProps<T = ${genericsTypes}> = ${componentName}Variables & {
412
+ options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
420
413
  }
421
- interface ${componentName}MutationProps<T> {
414
+ export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
415
+ return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
416
+ { enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
417
+ );}
418
+
419
+ type ${componentName}MutationProps<T> = {
422
420
  options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
423
421
  }
424
422
  export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
425
- return useMutation(async ({${paramsInPath.join(', ')}}) => {
426
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`)
427
- return result.data
428
- },
423
+ return useMutation(async (data) => use${componentName}Query.fetch(data),
429
424
  props?.options
430
425
  )};`;
431
426
  }
432
427
  if (!requestBodyComponent && paramsInPath.length && queryParam && !headerParam) {
433
- output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
434
- ${paramsTypes};
428
+ output += `
429
+ type ${componentName}Variables = {
430
+ ${paramsTypes}
435
431
  ${queryParamsType};
436
- options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
437
432
  }
438
- export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
439
- return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props), { enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
440
- );}
441
-
433
+
442
434
  use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'>) => {
443
435
  const {${paramsInPath.join(', ')}, ...queryParams} = props
444
436
  const params = queryString.stringify(queryParams);
@@ -447,105 +439,78 @@ const generateRestfulComponent = (operation, verb, route, operationIds, paramete
447
439
  }
448
440
 
449
441
  use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
450
-
451
442
  use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'>): QueryKey => [...use${componentName}Query.baseKey(), params];
452
-
453
- `;
454
- output += `interface ${componentName}MutationVariables {
455
- ${paramsTypes}
456
- ${queryParamsType}
443
+
444
+
445
+ type ${componentName}QueryProps<T = ${genericsTypes}> ${componentName}Variables & {
446
+ options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
457
447
  }
458
- interface ${componentName}MutationProps<T> {
459
- options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
448
+ export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
449
+ return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props), { enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
450
+ );}
451
+
452
+ type ${componentName}MutationProps<T> = {
453
+ options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}Variables, T>
460
454
  }
461
455
  export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
462
- return useMutation(async (data) => {
463
- const {${paramsInPath.join(', ')}, ...queryParams} = data
464
- const params = queryString.stringify(queryParams);
465
- const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
466
- return result.data
467
- },
456
+ return useMutation(async (data) => use${componentName}Query.fetch(data),
468
457
  props?.options
469
458
  )};`;
470
459
  }
471
460
  if (!requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
472
- output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
461
+ output += `
462
+ use${componentName}Query.fetch = async () => {
463
+ const result = await api.${verb}<${genericsTypes}>(\`${route}\`);
464
+ return result.data;
465
+ }
466
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
467
+ use${componentName}Query.queryKey = (): QueryKey => use${componentName}Query.baseKey()
468
+
469
+ type ${componentName}QueryProps<T = ${genericsTypes}> = {
473
470
  options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
474
471
  }
475
472
  export function use${componentName}Query<T = ${genericsTypes}>(props?: ${componentName}QueryProps<T>) {
476
473
  return useQuery(use${componentName}Query.queryKey(), use${componentName}Query.fetch, props?.options
477
- );}
478
-
479
- use${componentName}Query.fetch = async () => {
480
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`);
481
- return result.data;
482
- }
474
+ );}
483
475
 
484
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
485
-
486
- use${componentName}Query.queryKey = (): QueryKey => use${componentName}Query.baseKey()
487
-
488
- `;
489
- output += `interface ${componentName}MutationProps<T> {
476
+ type ${componentName}MutationProps<T> = {
490
477
  options?: UseMutationOptions<${genericsTypes}, AxiosError, void, T>
491
478
  }
492
479
  export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
493
- return useMutation(async () => {
494
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`);
495
- return result.data;
496
- },
480
+ return useMutation(async () => use${componentName}Query.fetch(),
497
481
  props?.options
498
482
  )};`;
499
483
  }
500
484
  if (!requestBodyComponent && !paramsInPath.length && queryParam && !headerParam) {
501
- output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
502
- ${queryParamsType};
503
- options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
485
+ output += `
486
+ type ${componentName}Variables = {
487
+ ${queryParamsType}
504
488
  }
505
- export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
506
- return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
507
- { enabled: !!props.${queryParams.map((param) => param.name).join(' && !!props.')}, ...options }
508
- );}
509
-
510
- use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'>) => {
489
+
490
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
491
+ use${componentName}Query.queryKey = (params: ${componentName}Variables ): QueryKey => [...use${componentName}Query.baseKey(), params];
492
+ use${componentName}Query.fetch = async (props: ${componentName}Variables) => {
511
493
  const params = queryString.stringify({${queryParams
512
- .map((param) => `${param.name}: props.${param.name}`)
494
+ .map((param) => `"${param.name}": props["${param.name}"]`)
513
495
  .join(',')}});
514
496
  const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
515
497
  return result.data;
516
498
  }
517
499
 
518
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
519
-
520
- use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
500
+ export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}Variables & { options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>}) {
501
+ return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
502
+ { enabled: !!props${queryParams.map((param) => `["${param.name}"]`).join(' && !!props')}, ...options }
503
+ );}
521
504
 
522
- `;
523
- output += `interface ${componentName}MutationVariables {
524
- ${queryParamsType}
525
- }
526
- interface ${componentName}MutationProps<T> {
527
- options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
528
- }
529
-
530
- export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
531
- return useMutation(async (data) => {
532
- const params = queryString.stringify({${queryParams
533
- .map((param) => `${param.name}: data.${param.name}`)
534
- .join(',')}});
535
- const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
536
- return result.data;
537
- },
538
- props?.options
539
- )};`;
505
+ export function use${componentName}Mutation<T = ${genericsTypes}>(props?: { options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}Variables, T>}) {
506
+ return useMutation(async (data) => use${componentName}Query.fetch(data),
507
+ props?.options
508
+ )};
509
+ `;
540
510
  }
541
511
  if (requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
542
- output += `type ${componentName}QueryVariables = ${requestBodyComponent};
543
- interface ${componentName}QueryProps<T = ${genericsTypes}> extends ${componentName}QueryVariables {
544
- options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
545
- }
546
- export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...body }: ${componentName}QueryProps<T>) {
547
- return useQuery(use${componentName}Query.queryKey(body), async () => use${componentName}Query.fetch(body), options
548
- );}
512
+ output += `
513
+ type ${componentName}QueryVariables = ${requestBodyComponent};
549
514
 
550
515
  use${componentName}Query.fetch = async (body: Omit<${componentName}QueryProps, 'options'>) => {
551
516
  const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
@@ -553,46 +518,49 @@ const generateRestfulComponent = (operation, verb, route, operationIds, paramete
553
518
  }
554
519
 
555
520
  use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
556
-
557
521
  use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
558
522
 
559
- `;
560
- output += `type ${componentName}MutationVariables = ${requestBodyComponent};
561
- interface ${componentName}MutationProps<T> {
523
+ type ${componentName}QueryProps<T = ${genericsTypes}> = ${componentName}QueryVariables & {
524
+ options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
525
+ }
526
+ export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...body }: ${componentName}QueryProps<T>) {
527
+ return useQuery(use${componentName}Query.queryKey(body), async () => use${componentName}Query.fetch(body), options
528
+ );}
529
+
530
+
531
+
532
+ type ${componentName}MutationVariables = ${requestBodyComponent};
533
+ type ${componentName}MutationProps<T> = {
562
534
  options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
563
535
  }
564
536
  export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
565
- return useMutation(async (body) => {
566
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
567
- return result.data
568
- },
537
+ return useMutation(async (body) => use${componentName}Query.fetch(body),
569
538
  props?.options
570
539
  )};`;
571
540
  }
572
541
  if (requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
573
- output += `interface ${componentName}QueryProps<T = ${genericsTypes}> extends ${requestBodyComponent
542
+ output += `
543
+ type ${componentName}QueryProps<T = ${genericsTypes}> = ${requestBodyComponent
574
544
  .replace('{', '')
575
- .replace('}', '')} {
545
+ .replace('}', '')} & {
576
546
  ${paramsTypes};
577
547
  options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
578
548
  }
579
- export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
580
- return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props), { enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
581
- );}
582
549
 
583
550
  use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'>) => {
584
551
  const {${paramsInPath.join(', ')}, ...body} = props
585
552
  const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
586
553
  return result.data
587
554
  }
588
-
589
555
  use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
590
-
591
556
  use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
592
557
 
593
- `;
594
- output += `type ${componentName}MutationVariables = {${paramsTypes}} & ${requestBodyComponent}
595
- interface ${componentName}MutationProps<T> {
558
+ export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
559
+ return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props), { enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
560
+ );}
561
+
562
+ type ${componentName}MutationVariables = {${paramsTypes}} & ${requestBodyComponent}
563
+ type ${componentName}MutationProps<T> = {
596
564
  options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
597
565
  }
598
566
  export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
@@ -614,9 +582,20 @@ const generateRestfulComponent = (operation, verb, route, operationIds, paramete
614
582
  }
615
583
  if (!requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
616
584
  output += `
617
- // HELLO
618
- type ${componentName}HeaderVariables = {${headerParam}};
619
- type ${componentName}QueryProps<T = ${genericsTypes}> = ${componentName}HeaderVariables & {
585
+ type ${componentName}Variables = {
586
+ ${headerParam}
587
+ };
588
+
589
+ use${componentName}Query.fetch = async (headers: ${componentName}Variables) => {
590
+ const result = await api.${verb}<${genericsTypes}>(\`${route}\`, {headers: headers});
591
+ return result.data;
592
+ }
593
+
594
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
595
+
596
+ use${componentName}Query.queryKey = (params: ${componentName}Variables ): QueryKey => [...use${componentName}Query.baseKey(), params];
597
+
598
+ type ${componentName}QueryProps<T = ${genericsTypes}> = ${componentName}Variables & {
620
599
  options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
621
600
  }
622
601
  export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
@@ -624,95 +603,86 @@ const generateRestfulComponent = (operation, verb, route, operationIds, paramete
624
603
  { enabled: !!props${headerParams.map((param) => `["${param.name}"]`).join(' && !!props')}, ...options }
625
604
  );}
626
605
 
627
- use${componentName}Query.fetch = async (headers: ${componentName}HeaderVariables) => {
628
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`, {headers: headers});
629
- return result.data;
630
- }
631
-
632
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
633
606
 
634
- use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
635
607
 
636
608
  type ${componentName}MutationProps<T> = {
637
- options?: UseMutationOptions<${genericsTypes}, AxiosError, void, T>
609
+ options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}Variables, T>
638
610
  }
639
611
  export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
640
- return useMutation(async () => {
641
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`);
642
- return result.data;
643
- },
612
+ return useMutation(async (data) => use${componentName}Query.fetch(data),
644
613
  props?.options
645
614
  )};`;
646
615
  }
647
616
  if (!requestBodyComponent && !paramsInPath.length && queryParam && headerParam) {
648
- output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
617
+ output += `
618
+ type ${componentName}Variables = {
619
+ ${headerParam}
649
620
  ${queryParamsType};
621
+ };
622
+
623
+ use${componentName}Query.fetch = async (data: ${componentName}Variables) => {
624
+ const params = queryString.stringify({
625
+ ${queryParams.map((param) => `${param.name}: data.${param.name}`).join(',')}
626
+ });
627
+ const headers = {
628
+ ${headerParams.map((param) => `"${param.name}": data["${param.name}"]`).join(',')}
629
+ }
630
+ const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`, {headers})
631
+ return result.data;
632
+ }
633
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
634
+ use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
635
+
636
+ type ${componentName}QueryProps<T = ${genericsTypes}> = ${componentName}Variables & {
650
637
  options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
651
638
  }
652
639
  export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
653
640
  return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
654
- { enabled: !!props.${queryParams.map((param) => param.name).join(' && !!props.')}, ...options }
641
+ { enabled: !!props${[...queryParams, ...headerParams]
642
+ .map((param) => `["${param.name}"]`)
643
+ .join(' && !!props')}, ...options }
655
644
  );}
656
645
 
657
- use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'>) => {
658
- const params = queryString.stringify({${queryParams
659
- .map((param) => `${param.name}: props.${param.name}`)
660
- .join(',')}});
661
- const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
662
- return result.data;
663
- }
664
-
665
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
666
-
667
- use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
668
-
669
- interface ${componentName}MutationVariables {
670
- ${queryParamsType}
671
- }
672
- interface ${componentName}MutationProps<T> {
673
- options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
646
+ type ${componentName}MutationProps<T> = {
647
+ options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}Variables, T>
674
648
  }
675
649
 
676
650
  export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
677
- return useMutation(async (data) => {
678
- const params = queryString.stringify({${queryParams
679
- .map((param) => `${param.name}: data.${param.name}`)
680
- .join(',')}});
681
- const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
682
- return result.data;
683
- },
651
+ return useMutation(async (data) => use${componentName}Query.fetch(data),
684
652
  props?.options
685
653
  )};`;
686
654
  }
687
655
  if (requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
688
656
  output += `
689
- type ${componentName}QueryVariables = ${requestBodyComponent};
690
- interface ${componentName}QueryProps<T = ${genericsTypes}> extends ${componentName}QueryVariables {
691
- options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
692
- }
693
- export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...body }: ${componentName}QueryProps<T>) {
694
- return useQuery(use${componentName}Query.queryKey(body), async () => use${componentName}Query.fetch(body), options
695
- );}
657
+ type ${componentName}Variables = ${requestBodyComponent} & {
658
+ ${headerParam}
659
+ };
696
660
 
697
- use${componentName}Query.fetch = async (body: Omit<${componentName}QueryProps, 'options'>) => {
698
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
661
+ use${componentName}Query.fetch = async (body: ${componentName}Variables) => {
662
+ const headers = {
663
+ ${headerParams.map((param) => `"${param.name}": body["${param.name}"]`).join(',')}
664
+ }
665
+ const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body, {headers})
699
666
  return result.data
700
667
  }
701
-
702
668
  use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
669
+ use${componentName}Query.queryKey = (params: ${componentName}Variables ): QueryKey => [...use${componentName}Query.baseKey(), params];
670
+
671
+ type ${componentName}QueryProps<T = ${genericsTypes}> = ${componentName}Variables & {
672
+ options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
673
+ }
674
+ export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...body }: ${componentName}QueryProps<T>) {
675
+ return useQuery(use${componentName}Query.queryKey(body), async () => use${componentName}Query.fetch(body),{ enabled: !!body${headerParams
676
+ .map((param) => `["${param.name}"]`)
677
+ .join(' && !!props')}, ...options }
678
+ );}
703
679
 
704
- use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
705
-
706
- type ${componentName}MutationVariables = ${requestBodyComponent};
707
680
 
708
- interface ${componentName}MutationProps<T> {
709
- options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
681
+ type ${componentName}MutationProps<T> = {
682
+ options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}Variables, T>
710
683
  }
711
684
  export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
712
- return useMutation(async (body) => {
713
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
714
- return result.data
715
- },
685
+ return useMutation(async (body) => use${componentName}Query.fetch(body),
716
686
  props?.options
717
687
  )};`;
718
688
  }
@@ -722,33 +692,51 @@ const generateRestfulComponent = (operation, verb, route, operationIds, paramete
722
692
  return output;
723
693
  };
724
694
  exports.generateRestfulComponent = generateRestfulComponent;
695
+ const generateQueryHooks = (paths, operationIds, schemasComponents, headerFilters) => {
696
+ let output = '';
697
+ Object.entries(paths).forEach(([route, verbs]) => {
698
+ Object.entries(verbs).forEach(([verb, operation]) => {
699
+ if (['get', 'post', 'patch', 'put', 'delete'].includes(verb) && !operation.deprecated) {
700
+ output += (0, exports.generateRestfulComponent)({
701
+ operation,
702
+ verb,
703
+ route,
704
+ operationIds,
705
+ parameters: verbs.parameters,
706
+ schemasComponents,
707
+ headerFilters,
708
+ });
709
+ }
710
+ });
711
+ });
712
+ return output;
713
+ };
725
714
  /**
726
715
  * Main entry of the generator. Generate react-query component from openAPI.
727
716
  */
728
- const importOpenApi = async ({ data, format, apiDir, }) => {
717
+ const importOpenApi = async ({ data, format, apiDir, headerFilters = [], }) => {
729
718
  const operationIds = [];
730
719
  let specs = await importSpecs(data, format);
731
720
  (0, exports.resolveDiscriminator)(specs);
732
- let output = `
721
+ let output = '';
722
+ output = `
733
723
  import { useQuery, useMutation, UseQueryOptions, UseMutationOptions, QueryKey } from 'react-query';
734
724
  import queryString from 'query-string';
735
725
  import {AxiosError} from 'axios';
736
726
  import { api } from '${apiDir}';
727
+
728
+ // SCEHMAS
729
+ ${(0, exports.generateSchemasDefinition)(specs.components?.schemas)}
730
+
731
+ // RESPONSES
732
+ ${(0, exports.generateResponsesDefinition)(specs.components?.responses)}
733
+
734
+ // REQUEST BODIES
735
+ ${(0, exports.generateRequestBodiesDefinition)(specs.components?.requestBodies)}
736
+
737
+ // HOOKS
738
+ ${generateQueryHooks(specs.paths, operationIds, specs.components, headerFilters)}
737
739
  `;
738
- output += '\n\n// SCEHMAS\n';
739
- output += (0, exports.generateSchemasDefinition)(specs.components && specs.components.schemas);
740
- output += '\n\n// RESPONSES\n';
741
- output += (0, exports.generateResponsesDefinition)(specs.components && specs.components.responses);
742
- output += '\n\n// REQUEST BODIES\n';
743
- output += (0, exports.generateRequestBodiesDefinition)(specs.components && specs.components.requestBodies);
744
- output += '\n\n// HOOKS\n';
745
- Object.entries(specs.paths).forEach(([route, verbs]) => {
746
- Object.entries(verbs).forEach(([verb, operation]) => {
747
- if (['get', 'post', 'patch', 'put', 'delete'].includes(verb) && !operation.deprecated) {
748
- output += (0, exports.generateRestfulComponent)(operation, verb, route, operationIds, verbs.parameters, specs.components);
749
- }
750
- });
751
- });
752
740
  return output;
753
741
  };
754
742
  exports.importOpenApi = importOpenApi;
@@ -10,7 +10,7 @@ const path_1 = require("path");
10
10
  const import_open_api_1 = require("./import-open-api");
11
11
  const log = console.log; // tslint:disable-line:no-console
12
12
  const createSuccessMessage = (backend) => chalk_1.default.green(`🎉 ${backend ? `[${backend}] ` : ''} Your OpenAPI spec has been converted into react query hooks`);
13
- function importSpecs({ sourceDirectory, exportDirectory, apiDirectory, }) {
13
+ function importSpecs({ sourceDirectory, exportDirectory, apiDirectory, headerFilters, }) {
14
14
  (0, fs_1.readdir)(sourceDirectory, function (err, filenames) {
15
15
  if (err) {
16
16
  throw err;
@@ -21,7 +21,7 @@ function importSpecs({ sourceDirectory, exportDirectory, apiDirectory, }) {
21
21
  const format = ['.yaml', '.yml'].includes(ext.toLowerCase()) ? 'yaml' : 'json';
22
22
  try {
23
23
  const name = `useQueries${filename.split('.')[0]}.tsx`;
24
- const fileExports = await (0, import_open_api_1.importOpenApi)({ data, format, apiDir: apiDirectory });
24
+ const fileExports = await (0, import_open_api_1.importOpenApi)({ data, format, apiDir: apiDirectory, headerFilters });
25
25
  (0, fs_1.writeFileSync)((0, path_1.join)(process.cwd(), `${exportDirectory}/${name}`), fileExports);
26
26
  log(createSuccessMessage(filename));
27
27
  }
@@ -287,12 +287,12 @@ export const formatDescription = (description, tabSize = 0) => description
287
287
  ? `/**\n${description
288
288
  .split('\n')
289
289
  .map((i) => `${' '.repeat(tabSize)} * ${i}`)
290
- .join('\n')}\n${' '.repeat(tabSize)} */\n${' '.repeat(tabSize)}`
290
+ .join('\n')}\n${' '.repeat(tabSize)} */${' '.repeat(tabSize)}`
291
291
  : '';
292
292
  /**
293
293
  * Generate a react-query component from openapi operation specs
294
294
  */
295
- export const generateRestfulComponent = (operation, verb, route, operationIds, parameters = [], schemasComponents) => {
295
+ export const generateRestfulComponent = ({ operation, verb, route, operationIds, parameters, schemasComponents, headerFilters, }) => {
296
296
  const { operationId = route.replace('/', '') } = operation;
297
297
  if (operationId === '*') {
298
298
  throw new Error(`Invalid operationId/Route set for ${verb} ${route}`);
@@ -310,7 +310,7 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
310
310
  const requestBodyTypes = getResReqTypes([['body', operation.requestBody]]);
311
311
  const needAResponseComponent = true;
312
312
  const paramsInPath = getParamsInPath(route).filter((param) => !(verb === 'delete' && param === lastParamInTheRoute));
313
- const { query: queryParams = [], path: pathParams = [], header: headerParams = [] } = groupBy([...parameters, ...(operation.parameters || [])].map((p) => {
313
+ const { query: queryParams = [], path: pathParams = [], header = [], } = groupBy([...(parameters || []), ...(operation.parameters || [])].map((p) => {
314
314
  if (isReference(p)) {
315
315
  return get(schemasComponents, p.$ref.replace('#/components/', '').replace('/', '.'));
316
316
  }
@@ -318,6 +318,7 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
318
318
  return p;
319
319
  }
320
320
  }), 'in');
321
+ const headerParams = header.filter((p) => !headerFilters?.includes(p.name));
321
322
  const paramsTypes = paramsInPath
322
323
  .map((p) => {
323
324
  try {
@@ -373,52 +374,43 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
373
374
  const headerParam = headerType && headerType !== 'void' ? `${headerType};` : '';
374
375
  const queryParam = queryParamsType && queryParamsType !== 'void' ? `${queryParamsType}` : '';
375
376
  const requestBodyComponent = requestBodyTypes && requestBodyTypes !== 'void' ? `${requestBodyTypes}` : '';
376
- console.log(headerParam);
377
377
  // QUERIES
378
378
  if (!requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
379
- output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
380
- ${paramsTypes};
381
- options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
379
+ output += `
380
+ type ${componentName}Variables = {
381
+ ${paramsTypes}
382
382
  }
383
- export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
384
- return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
385
- { enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
386
- );}
387
383
 
388
384
  use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'> ) => {
389
385
  const result = await api.${verb}<${genericsTypes}>(\`${route.replace(/\{/g, '{props.')}\`);
390
386
  return result.data;
391
387
  }
392
-
393
388
  use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
389
+ use${componentName}Query.queryKey = (params: ${componentName}Variables ): QueryKey => [...use${componentName}Query.baseKey(), params];
394
390
 
395
- use${componentName}Query.queryKey = (params: {${paramsTypes}} ): QueryKey => [...use${componentName}Query.baseKey(), params];
396
-
397
- `;
398
- output += `interface ${componentName}MutationVariables {
399
- ${paramsTypes}
391
+ type ${componentName}QueryProps<T = ${genericsTypes}> = ${componentName}Variables & {
392
+ options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
400
393
  }
401
- interface ${componentName}MutationProps<T> {
394
+ export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
395
+ return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
396
+ { enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
397
+ );}
398
+
399
+ type ${componentName}MutationProps<T> = {
402
400
  options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
403
401
  }
404
402
  export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
405
- return useMutation(async ({${paramsInPath.join(', ')}}) => {
406
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`)
407
- return result.data
408
- },
403
+ return useMutation(async (data) => use${componentName}Query.fetch(data),
409
404
  props?.options
410
405
  )};`;
411
406
  }
412
407
  if (!requestBodyComponent && paramsInPath.length && queryParam && !headerParam) {
413
- output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
414
- ${paramsTypes};
408
+ output += `
409
+ type ${componentName}Variables = {
410
+ ${paramsTypes}
415
411
  ${queryParamsType};
416
- options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
417
412
  }
418
- export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
419
- return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props), { enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
420
- );}
421
-
413
+
422
414
  use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'>) => {
423
415
  const {${paramsInPath.join(', ')}, ...queryParams} = props
424
416
  const params = queryString.stringify(queryParams);
@@ -427,105 +419,78 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
427
419
  }
428
420
 
429
421
  use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
430
-
431
422
  use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'>): QueryKey => [...use${componentName}Query.baseKey(), params];
432
-
433
- `;
434
- output += `interface ${componentName}MutationVariables {
435
- ${paramsTypes}
436
- ${queryParamsType}
423
+
424
+
425
+ type ${componentName}QueryProps<T = ${genericsTypes}> ${componentName}Variables & {
426
+ options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
437
427
  }
438
- interface ${componentName}MutationProps<T> {
439
- options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
428
+ export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
429
+ return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props), { enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
430
+ );}
431
+
432
+ type ${componentName}MutationProps<T> = {
433
+ options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}Variables, T>
440
434
  }
441
435
  export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
442
- return useMutation(async (data) => {
443
- const {${paramsInPath.join(', ')}, ...queryParams} = data
444
- const params = queryString.stringify(queryParams);
445
- const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
446
- return result.data
447
- },
436
+ return useMutation(async (data) => use${componentName}Query.fetch(data),
448
437
  props?.options
449
438
  )};`;
450
439
  }
451
440
  if (!requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
452
- output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
441
+ output += `
442
+ use${componentName}Query.fetch = async () => {
443
+ const result = await api.${verb}<${genericsTypes}>(\`${route}\`);
444
+ return result.data;
445
+ }
446
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
447
+ use${componentName}Query.queryKey = (): QueryKey => use${componentName}Query.baseKey()
448
+
449
+ type ${componentName}QueryProps<T = ${genericsTypes}> = {
453
450
  options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
454
451
  }
455
452
  export function use${componentName}Query<T = ${genericsTypes}>(props?: ${componentName}QueryProps<T>) {
456
453
  return useQuery(use${componentName}Query.queryKey(), use${componentName}Query.fetch, props?.options
457
- );}
458
-
459
- use${componentName}Query.fetch = async () => {
460
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`);
461
- return result.data;
462
- }
454
+ );}
463
455
 
464
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
465
-
466
- use${componentName}Query.queryKey = (): QueryKey => use${componentName}Query.baseKey()
467
-
468
- `;
469
- output += `interface ${componentName}MutationProps<T> {
456
+ type ${componentName}MutationProps<T> = {
470
457
  options?: UseMutationOptions<${genericsTypes}, AxiosError, void, T>
471
458
  }
472
459
  export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
473
- return useMutation(async () => {
474
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`);
475
- return result.data;
476
- },
460
+ return useMutation(async () => use${componentName}Query.fetch(),
477
461
  props?.options
478
462
  )};`;
479
463
  }
480
464
  if (!requestBodyComponent && !paramsInPath.length && queryParam && !headerParam) {
481
- output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
482
- ${queryParamsType};
483
- options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
465
+ output += `
466
+ type ${componentName}Variables = {
467
+ ${queryParamsType}
484
468
  }
485
- export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
486
- return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
487
- { enabled: !!props.${queryParams.map((param) => param.name).join(' && !!props.')}, ...options }
488
- );}
489
-
490
- use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'>) => {
469
+
470
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
471
+ use${componentName}Query.queryKey = (params: ${componentName}Variables ): QueryKey => [...use${componentName}Query.baseKey(), params];
472
+ use${componentName}Query.fetch = async (props: ${componentName}Variables) => {
491
473
  const params = queryString.stringify({${queryParams
492
- .map((param) => `${param.name}: props.${param.name}`)
474
+ .map((param) => `"${param.name}": props["${param.name}"]`)
493
475
  .join(',')}});
494
476
  const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
495
477
  return result.data;
496
478
  }
497
479
 
498
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
499
-
500
- use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
480
+ export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}Variables & { options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>}) {
481
+ return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
482
+ { enabled: !!props${queryParams.map((param) => `["${param.name}"]`).join(' && !!props')}, ...options }
483
+ );}
501
484
 
502
- `;
503
- output += `interface ${componentName}MutationVariables {
504
- ${queryParamsType}
505
- }
506
- interface ${componentName}MutationProps<T> {
507
- options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
508
- }
509
-
510
- export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
511
- return useMutation(async (data) => {
512
- const params = queryString.stringify({${queryParams
513
- .map((param) => `${param.name}: data.${param.name}`)
514
- .join(',')}});
515
- const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
516
- return result.data;
517
- },
518
- props?.options
519
- )};`;
485
+ export function use${componentName}Mutation<T = ${genericsTypes}>(props?: { options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}Variables, T>}) {
486
+ return useMutation(async (data) => use${componentName}Query.fetch(data),
487
+ props?.options
488
+ )};
489
+ `;
520
490
  }
521
491
  if (requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
522
- output += `type ${componentName}QueryVariables = ${requestBodyComponent};
523
- interface ${componentName}QueryProps<T = ${genericsTypes}> extends ${componentName}QueryVariables {
524
- options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
525
- }
526
- export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...body }: ${componentName}QueryProps<T>) {
527
- return useQuery(use${componentName}Query.queryKey(body), async () => use${componentName}Query.fetch(body), options
528
- );}
492
+ output += `
493
+ type ${componentName}QueryVariables = ${requestBodyComponent};
529
494
 
530
495
  use${componentName}Query.fetch = async (body: Omit<${componentName}QueryProps, 'options'>) => {
531
496
  const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
@@ -533,46 +498,49 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
533
498
  }
534
499
 
535
500
  use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
536
-
537
501
  use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
538
502
 
539
- `;
540
- output += `type ${componentName}MutationVariables = ${requestBodyComponent};
541
- interface ${componentName}MutationProps<T> {
503
+ type ${componentName}QueryProps<T = ${genericsTypes}> = ${componentName}QueryVariables & {
504
+ options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
505
+ }
506
+ export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...body }: ${componentName}QueryProps<T>) {
507
+ return useQuery(use${componentName}Query.queryKey(body), async () => use${componentName}Query.fetch(body), options
508
+ );}
509
+
510
+
511
+
512
+ type ${componentName}MutationVariables = ${requestBodyComponent};
513
+ type ${componentName}MutationProps<T> = {
542
514
  options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
543
515
  }
544
516
  export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
545
- return useMutation(async (body) => {
546
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
547
- return result.data
548
- },
517
+ return useMutation(async (body) => use${componentName}Query.fetch(body),
549
518
  props?.options
550
519
  )};`;
551
520
  }
552
521
  if (requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
553
- output += `interface ${componentName}QueryProps<T = ${genericsTypes}> extends ${requestBodyComponent
522
+ output += `
523
+ type ${componentName}QueryProps<T = ${genericsTypes}> = ${requestBodyComponent
554
524
  .replace('{', '')
555
- .replace('}', '')} {
525
+ .replace('}', '')} & {
556
526
  ${paramsTypes};
557
527
  options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
558
528
  }
559
- export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
560
- return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props), { enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
561
- );}
562
529
 
563
530
  use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'>) => {
564
531
  const {${paramsInPath.join(', ')}, ...body} = props
565
532
  const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
566
533
  return result.data
567
534
  }
568
-
569
535
  use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
570
-
571
536
  use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
572
537
 
573
- `;
574
- output += `type ${componentName}MutationVariables = {${paramsTypes}} & ${requestBodyComponent}
575
- interface ${componentName}MutationProps<T> {
538
+ export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
539
+ return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props), { enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
540
+ );}
541
+
542
+ type ${componentName}MutationVariables = {${paramsTypes}} & ${requestBodyComponent}
543
+ type ${componentName}MutationProps<T> = {
576
544
  options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
577
545
  }
578
546
  export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
@@ -594,9 +562,20 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
594
562
  }
595
563
  if (!requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
596
564
  output += `
597
- // HELLO
598
- type ${componentName}HeaderVariables = {${headerParam}};
599
- type ${componentName}QueryProps<T = ${genericsTypes}> = ${componentName}HeaderVariables & {
565
+ type ${componentName}Variables = {
566
+ ${headerParam}
567
+ };
568
+
569
+ use${componentName}Query.fetch = async (headers: ${componentName}Variables) => {
570
+ const result = await api.${verb}<${genericsTypes}>(\`${route}\`, {headers: headers});
571
+ return result.data;
572
+ }
573
+
574
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
575
+
576
+ use${componentName}Query.queryKey = (params: ${componentName}Variables ): QueryKey => [...use${componentName}Query.baseKey(), params];
577
+
578
+ type ${componentName}QueryProps<T = ${genericsTypes}> = ${componentName}Variables & {
600
579
  options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
601
580
  }
602
581
  export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
@@ -604,95 +583,86 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
604
583
  { enabled: !!props${headerParams.map((param) => `["${param.name}"]`).join(' && !!props')}, ...options }
605
584
  );}
606
585
 
607
- use${componentName}Query.fetch = async (headers: ${componentName}HeaderVariables) => {
608
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`, {headers: headers});
609
- return result.data;
610
- }
611
-
612
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
613
586
 
614
- use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
615
587
 
616
588
  type ${componentName}MutationProps<T> = {
617
- options?: UseMutationOptions<${genericsTypes}, AxiosError, void, T>
589
+ options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}Variables, T>
618
590
  }
619
591
  export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
620
- return useMutation(async () => {
621
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`);
622
- return result.data;
623
- },
592
+ return useMutation(async (data) => use${componentName}Query.fetch(data),
624
593
  props?.options
625
594
  )};`;
626
595
  }
627
596
  if (!requestBodyComponent && !paramsInPath.length && queryParam && headerParam) {
628
- output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
597
+ output += `
598
+ type ${componentName}Variables = {
599
+ ${headerParam}
629
600
  ${queryParamsType};
601
+ };
602
+
603
+ use${componentName}Query.fetch = async (data: ${componentName}Variables) => {
604
+ const params = queryString.stringify({
605
+ ${queryParams.map((param) => `${param.name}: data.${param.name}`).join(',')}
606
+ });
607
+ const headers = {
608
+ ${headerParams.map((param) => `"${param.name}": data["${param.name}"]`).join(',')}
609
+ }
610
+ const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`, {headers})
611
+ return result.data;
612
+ }
613
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
614
+ use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
615
+
616
+ type ${componentName}QueryProps<T = ${genericsTypes}> = ${componentName}Variables & {
630
617
  options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
631
618
  }
632
619
  export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
633
620
  return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
634
- { enabled: !!props.${queryParams.map((param) => param.name).join(' && !!props.')}, ...options }
621
+ { enabled: !!props${[...queryParams, ...headerParams]
622
+ .map((param) => `["${param.name}"]`)
623
+ .join(' && !!props')}, ...options }
635
624
  );}
636
625
 
637
- use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'>) => {
638
- const params = queryString.stringify({${queryParams
639
- .map((param) => `${param.name}: props.${param.name}`)
640
- .join(',')}});
641
- const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
642
- return result.data;
643
- }
644
-
645
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
646
-
647
- use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
648
-
649
- interface ${componentName}MutationVariables {
650
- ${queryParamsType}
651
- }
652
- interface ${componentName}MutationProps<T> {
653
- options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
626
+ type ${componentName}MutationProps<T> = {
627
+ options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}Variables, T>
654
628
  }
655
629
 
656
630
  export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
657
- return useMutation(async (data) => {
658
- const params = queryString.stringify({${queryParams
659
- .map((param) => `${param.name}: data.${param.name}`)
660
- .join(',')}});
661
- const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
662
- return result.data;
663
- },
631
+ return useMutation(async (data) => use${componentName}Query.fetch(data),
664
632
  props?.options
665
633
  )};`;
666
634
  }
667
635
  if (requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
668
636
  output += `
669
- type ${componentName}QueryVariables = ${requestBodyComponent};
670
- interface ${componentName}QueryProps<T = ${genericsTypes}> extends ${componentName}QueryVariables {
671
- options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
672
- }
673
- export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...body }: ${componentName}QueryProps<T>) {
674
- return useQuery(use${componentName}Query.queryKey(body), async () => use${componentName}Query.fetch(body), options
675
- );}
637
+ type ${componentName}Variables = ${requestBodyComponent} & {
638
+ ${headerParam}
639
+ };
676
640
 
677
- use${componentName}Query.fetch = async (body: Omit<${componentName}QueryProps, 'options'>) => {
678
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
641
+ use${componentName}Query.fetch = async (body: ${componentName}Variables) => {
642
+ const headers = {
643
+ ${headerParams.map((param) => `"${param.name}": body["${param.name}"]`).join(',')}
644
+ }
645
+ const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body, {headers})
679
646
  return result.data
680
647
  }
681
-
682
648
  use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
649
+ use${componentName}Query.queryKey = (params: ${componentName}Variables ): QueryKey => [...use${componentName}Query.baseKey(), params];
650
+
651
+ type ${componentName}QueryProps<T = ${genericsTypes}> = ${componentName}Variables & {
652
+ options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
653
+ }
654
+ export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...body }: ${componentName}QueryProps<T>) {
655
+ return useQuery(use${componentName}Query.queryKey(body), async () => use${componentName}Query.fetch(body),{ enabled: !!body${headerParams
656
+ .map((param) => `["${param.name}"]`)
657
+ .join(' && !!props')}, ...options }
658
+ );}
683
659
 
684
- use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
685
-
686
- type ${componentName}MutationVariables = ${requestBodyComponent};
687
660
 
688
- interface ${componentName}MutationProps<T> {
689
- options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
661
+ type ${componentName}MutationProps<T> = {
662
+ options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}Variables, T>
690
663
  }
691
664
  export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
692
- return useMutation(async (body) => {
693
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
694
- return result.data
695
- },
665
+ return useMutation(async (body) => use${componentName}Query.fetch(body),
696
666
  props?.options
697
667
  )};`;
698
668
  }
@@ -701,32 +671,50 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
701
671
  }
702
672
  return output;
703
673
  };
674
+ const generateQueryHooks = (paths, operationIds, schemasComponents, headerFilters) => {
675
+ let output = '';
676
+ Object.entries(paths).forEach(([route, verbs]) => {
677
+ Object.entries(verbs).forEach(([verb, operation]) => {
678
+ if (['get', 'post', 'patch', 'put', 'delete'].includes(verb) && !operation.deprecated) {
679
+ output += generateRestfulComponent({
680
+ operation,
681
+ verb,
682
+ route,
683
+ operationIds,
684
+ parameters: verbs.parameters,
685
+ schemasComponents,
686
+ headerFilters,
687
+ });
688
+ }
689
+ });
690
+ });
691
+ return output;
692
+ };
704
693
  /**
705
694
  * Main entry of the generator. Generate react-query component from openAPI.
706
695
  */
707
- export const importOpenApi = async ({ data, format, apiDir, }) => {
696
+ export const importOpenApi = async ({ data, format, apiDir, headerFilters = [], }) => {
708
697
  const operationIds = [];
709
698
  let specs = await importSpecs(data, format);
710
699
  resolveDiscriminator(specs);
711
- let output = `
700
+ let output = '';
701
+ output = `
712
702
  import { useQuery, useMutation, UseQueryOptions, UseMutationOptions, QueryKey } from 'react-query';
713
703
  import queryString from 'query-string';
714
704
  import {AxiosError} from 'axios';
715
705
  import { api } from '${apiDir}';
706
+
707
+ // SCEHMAS
708
+ ${generateSchemasDefinition(specs.components?.schemas)}
709
+
710
+ // RESPONSES
711
+ ${generateResponsesDefinition(specs.components?.responses)}
712
+
713
+ // REQUEST BODIES
714
+ ${generateRequestBodiesDefinition(specs.components?.requestBodies)}
715
+
716
+ // HOOKS
717
+ ${generateQueryHooks(specs.paths, operationIds, specs.components, headerFilters)}
716
718
  `;
717
- output += '\n\n// SCEHMAS\n';
718
- output += generateSchemasDefinition(specs.components && specs.components.schemas);
719
- output += '\n\n// RESPONSES\n';
720
- output += generateResponsesDefinition(specs.components && specs.components.responses);
721
- output += '\n\n// REQUEST BODIES\n';
722
- output += generateRequestBodiesDefinition(specs.components && specs.components.requestBodies);
723
- output += '\n\n// HOOKS\n';
724
- Object.entries(specs.paths).forEach(([route, verbs]) => {
725
- Object.entries(verbs).forEach(([verb, operation]) => {
726
- if (['get', 'post', 'patch', 'put', 'delete'].includes(verb) && !operation.deprecated) {
727
- output += generateRestfulComponent(operation, verb, route, operationIds, verbs.parameters, specs.components);
728
- }
729
- });
730
- });
731
719
  return output;
732
720
  };
@@ -4,7 +4,7 @@ import { join, parse } from 'path';
4
4
  import { importOpenApi } from './import-open-api';
5
5
  const log = console.log; // tslint:disable-line:no-console
6
6
  const createSuccessMessage = (backend) => chalk.green(`🎉 ${backend ? `[${backend}] ` : ''} Your OpenAPI spec has been converted into react query hooks`);
7
- export function importSpecs({ sourceDirectory, exportDirectory, apiDirectory, }) {
7
+ export function importSpecs({ sourceDirectory, exportDirectory, apiDirectory, headerFilters, }) {
8
8
  readdir(sourceDirectory, function (err, filenames) {
9
9
  if (err) {
10
10
  throw err;
@@ -15,7 +15,7 @@ export function importSpecs({ sourceDirectory, exportDirectory, apiDirectory, })
15
15
  const format = ['.yaml', '.yml'].includes(ext.toLowerCase()) ? 'yaml' : 'json';
16
16
  try {
17
17
  const name = `useQueries${filename.split('.')[0]}.tsx`;
18
- const fileExports = await importOpenApi({ data, format, apiDir: apiDirectory });
18
+ const fileExports = await importOpenApi({ data, format, apiDir: apiDirectory, headerFilters });
19
19
  writeFileSync(join(process.cwd(), `${exportDirectory}/${name}`), fileExports);
20
20
  log(createSuccessMessage(filename));
21
21
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-query-lightbase-codegen",
3
- "version": "0.0.11",
3
+ "version": "0.0.14",
4
4
  "license": "MIT",
5
5
  "main": "./lib/cjs/index.js",
6
6
  "module": "./lib/esm/index.js",
@@ -8,8 +8,9 @@
8
8
  "lib/"
9
9
  ],
10
10
  "scripts": {
11
+ "lint": "eslint . --ext .js,.jsx,.ts,.tsx",
11
12
  "tsc": "tsc -p tsconfig.json && tsc -p tsconfig-cjs.json",
12
- "test": "yarn tsc && node test/script.mjs"
13
+ "test": "yarn tsc && node test/script.mjs && eslint . --ext .js,.jsx,.ts,.tsx --fix"
13
14
  },
14
15
  "dependencies": {
15
16
  "axios": "0.27.2",
@@ -25,6 +26,7 @@
25
26
  "yamljs": "0.3.0"
26
27
  },
27
28
  "devDependencies": {
29
+ "@babel/core": "7.17.10",
28
30
  "@babel/eslint-parser": "7.17.0",
29
31
  "@react-native-community/eslint-config": "3.0.2",
30
32
  "@types/lodash": "4.14.182",
@@ -35,6 +37,7 @@
35
37
  "eslint": "8.15.0",
36
38
  "eslint-plugin-prettier": "4.0.0",
37
39
  "prettier": "2.6.2",
40
+ "react": "17.0.2",
38
41
  "typescript": "4.6.4"
39
42
  }
40
43
  }