react-query-lightbase-codegen 0.0.11 → 0.0.12

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,67 +439,58 @@ 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
+ // USE AS EXAMPLE
487
+ type ${componentName}Variables = {
488
+ ${queryParamsType}
504
489
  }
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'>) => {
490
+
491
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
492
+ use${componentName}Query.queryKey = (params: ${componentName}Variables ): QueryKey => [...use${componentName}Query.baseKey(), params];
493
+ use${componentName}Query.fetch = async (props: ${componentName}Variables) => {
511
494
  const params = queryString.stringify({${queryParams
512
495
  .map((param) => `${param.name}: props.${param.name}`)
513
496
  .join(',')}});
@@ -515,37 +498,20 @@ const generateRestfulComponent = (operation, verb, route, operationIds, paramete
515
498
  return result.data;
516
499
  }
517
500
 
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];
501
+ export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}Variables & { options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>}) {
502
+ return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
503
+ { enabled: !!props${queryParams.map((param) => `["${param.name}"]`).join(' && !!props')}, ...options }
504
+ );}
521
505
 
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
- )};`;
506
+ export function use${componentName}Mutation<T = ${genericsTypes}>(props?: { options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}Variables, T>}) {
507
+ return useMutation(async (data) => use${componentName}Query.fetch(data),
508
+ props?.options
509
+ )};
510
+ `;
540
511
  }
541
512
  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
- );}
513
+ output += `
514
+ type ${componentName}QueryVariables = ${requestBodyComponent};
549
515
 
550
516
  use${componentName}Query.fetch = async (body: Omit<${componentName}QueryProps, 'options'>) => {
551
517
  const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
@@ -553,46 +519,49 @@ const generateRestfulComponent = (operation, verb, route, operationIds, paramete
553
519
  }
554
520
 
555
521
  use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
556
-
557
522
  use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
558
523
 
559
- `;
560
- output += `type ${componentName}MutationVariables = ${requestBodyComponent};
561
- interface ${componentName}MutationProps<T> {
524
+ type ${componentName}QueryProps<T = ${genericsTypes}> = ${componentName}QueryVariables & {
525
+ options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
526
+ }
527
+ export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...body }: ${componentName}QueryProps<T>) {
528
+ return useQuery(use${componentName}Query.queryKey(body), async () => use${componentName}Query.fetch(body), options
529
+ );}
530
+
531
+
532
+
533
+ type ${componentName}MutationVariables = ${requestBodyComponent};
534
+ type ${componentName}MutationProps<T> = {
562
535
  options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
563
536
  }
564
537
  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
- },
538
+ return useMutation(async (body) => use${componentName}Query.fetch(body),
569
539
  props?.options
570
540
  )};`;
571
541
  }
572
542
  if (requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
573
- output += `interface ${componentName}QueryProps<T = ${genericsTypes}> extends ${requestBodyComponent
543
+ output += `
544
+ type ${componentName}QueryProps<T = ${genericsTypes}> = ${requestBodyComponent
574
545
  .replace('{', '')
575
- .replace('}', '')} {
546
+ .replace('}', '')} & {
576
547
  ${paramsTypes};
577
548
  options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
578
549
  }
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
550
 
583
551
  use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'>) => {
584
552
  const {${paramsInPath.join(', ')}, ...body} = props
585
553
  const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
586
554
  return result.data
587
555
  }
588
-
589
556
  use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
590
-
591
557
  use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
592
558
 
593
- `;
594
- output += `type ${componentName}MutationVariables = {${paramsTypes}} & ${requestBodyComponent}
595
- interface ${componentName}MutationProps<T> {
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
+
563
+ type ${componentName}MutationVariables = {${paramsTypes}} & ${requestBodyComponent}
564
+ type ${componentName}MutationProps<T> = {
596
565
  options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
597
566
  }
598
567
  export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
@@ -614,9 +583,21 @@ const generateRestfulComponent = (operation, verb, route, operationIds, paramete
614
583
  }
615
584
  if (!requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
616
585
  output += `
617
- // HELLO
618
- type ${componentName}HeaderVariables = {${headerParam}};
619
- type ${componentName}QueryProps<T = ${genericsTypes}> = ${componentName}HeaderVariables & {
586
+ // DONE
587
+ type ${componentName}Variables = {
588
+ ${headerParam}
589
+ };
590
+
591
+ use${componentName}Query.fetch = async (headers: ${componentName}Variables) => {
592
+ const result = await api.${verb}<${genericsTypes}>(\`${route}\`, {headers: headers});
593
+ return result.data;
594
+ }
595
+
596
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
597
+
598
+ use${componentName}Query.queryKey = (params: ${componentName}Variables ): QueryKey => [...use${componentName}Query.baseKey(), params];
599
+
600
+ type ${componentName}QueryProps<T = ${genericsTypes}> = ${componentName}Variables & {
620
601
  options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
621
602
  }
622
603
  export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
@@ -624,95 +605,89 @@ const generateRestfulComponent = (operation, verb, route, operationIds, paramete
624
605
  { enabled: !!props${headerParams.map((param) => `["${param.name}"]`).join(' && !!props')}, ...options }
625
606
  );}
626
607
 
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
608
 
634
- use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
635
609
 
636
610
  type ${componentName}MutationProps<T> = {
637
- options?: UseMutationOptions<${genericsTypes}, AxiosError, void, T>
611
+ options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}Variables, T>
638
612
  }
639
613
  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
- },
614
+ return useMutation(async (data) => use${componentName}Query.fetch(data),
644
615
  props?.options
645
616
  )};`;
646
617
  }
647
618
  if (!requestBodyComponent && !paramsInPath.length && queryParam && headerParam) {
648
- output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
619
+ output += `
620
+ // DONE
621
+ type ${componentName}Variables = {
622
+ ${headerParam}
649
623
  ${queryParamsType};
624
+ };
625
+
626
+ use${componentName}Query.fetch = async (data: ${componentName}Variables) => {
627
+ const params = queryString.stringify({
628
+ ${queryParams.map((param) => `${param.name}: data.${param.name}`).join(',')}
629
+ });
630
+ const headers = {
631
+ ${headerParams.map((param) => `"${param.name}": data["${param.name}"]`).join(',')}
632
+ }
633
+ // HIHI
634
+ const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`, {headers})
635
+ return result.data;
636
+ }
637
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
638
+ use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
639
+
640
+ type ${componentName}QueryProps<T = ${genericsTypes}> = ${componentName}Variables & {
650
641
  options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
651
642
  }
652
643
  export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
653
644
  return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
654
- { enabled: !!props.${queryParams.map((param) => param.name).join(' && !!props.')}, ...options }
645
+ { enabled: !!props${[...queryParams, ...headerParams]
646
+ .map((param) => `["${param.name}"]`)
647
+ .join(' && !!props')}, ...options }
655
648
  );}
656
649
 
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>
650
+ type ${componentName}MutationProps<T> = {
651
+ options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}Variables, T>
674
652
  }
675
653
 
676
654
  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
- },
655
+ return useMutation(async (data) => use${componentName}Query.fetch(data),
684
656
  props?.options
685
657
  )};`;
686
658
  }
687
659
  if (requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
688
660
  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
- );}
661
+ // HEHEHEHEHE
662
+ type ${componentName}Variables = ${requestBodyComponent} & {
663
+ ${headerParam}
664
+ };
696
665
 
697
- use${componentName}Query.fetch = async (body: Omit<${componentName}QueryProps, 'options'>) => {
698
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
666
+ use${componentName}Query.fetch = async (body: ${componentName}Variables) => {
667
+ const headers = {
668
+ ${headerParams.map((param) => `"${param.name}": body["${param.name}"]`).join(',')}
669
+ }
670
+ const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body, {headers})
699
671
  return result.data
700
672
  }
701
-
702
673
  use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
674
+ use${componentName}Query.queryKey = (params: ${componentName}Variables ): QueryKey => [...use${componentName}Query.baseKey(), params];
675
+
676
+ type ${componentName}QueryProps<T = ${genericsTypes}> = ${componentName}Variables & {
677
+ options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
678
+ }
679
+ export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...body }: ${componentName}QueryProps<T>) {
680
+ return useQuery(use${componentName}Query.queryKey(body), async () => use${componentName}Query.fetch(body),{ enabled: !!body${headerParams
681
+ .map((param) => `["${param.name}"]`)
682
+ .join(' && !!props')}, ...options }
683
+ );}
703
684
 
704
- use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
705
-
706
- type ${componentName}MutationVariables = ${requestBodyComponent};
707
685
 
708
- interface ${componentName}MutationProps<T> {
709
- options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
686
+ type ${componentName}MutationProps<T> = {
687
+ options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}Variables, T>
710
688
  }
711
689
  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
- },
690
+ return useMutation(async (body) => use${componentName}Query.fetch(body),
716
691
  props?.options
717
692
  )};`;
718
693
  }
@@ -722,33 +697,51 @@ const generateRestfulComponent = (operation, verb, route, operationIds, paramete
722
697
  return output;
723
698
  };
724
699
  exports.generateRestfulComponent = generateRestfulComponent;
700
+ const generateQueryHooks = (paths, operationIds, schemasComponents, headerFilters) => {
701
+ let output = '';
702
+ Object.entries(paths).forEach(([route, verbs]) => {
703
+ Object.entries(verbs).forEach(([verb, operation]) => {
704
+ if (['get', 'post', 'patch', 'put', 'delete'].includes(verb) && !operation.deprecated) {
705
+ output += (0, exports.generateRestfulComponent)({
706
+ operation,
707
+ verb,
708
+ route,
709
+ operationIds,
710
+ parameters: verbs.parameters,
711
+ schemasComponents,
712
+ headerFilters,
713
+ });
714
+ }
715
+ });
716
+ });
717
+ return output;
718
+ };
725
719
  /**
726
720
  * Main entry of the generator. Generate react-query component from openAPI.
727
721
  */
728
- const importOpenApi = async ({ data, format, apiDir, }) => {
722
+ const importOpenApi = async ({ data, format, apiDir, headerFilters = [], }) => {
729
723
  const operationIds = [];
730
724
  let specs = await importSpecs(data, format);
731
725
  (0, exports.resolveDiscriminator)(specs);
732
- let output = `
726
+ let output = '';
727
+ output = `
733
728
  import { useQuery, useMutation, UseQueryOptions, UseMutationOptions, QueryKey } from 'react-query';
734
729
  import queryString from 'query-string';
735
730
  import {AxiosError} from 'axios';
736
731
  import { api } from '${apiDir}';
732
+
733
+ // SCEHMAS
734
+ ${(0, exports.generateSchemasDefinition)(specs.components?.schemas)}
735
+
736
+ // RESPONSES
737
+ ${(0, exports.generateResponsesDefinition)(specs.components?.responses)}
738
+
739
+ // REQUEST BODIES
740
+ ${(0, exports.generateRequestBodiesDefinition)(specs.components?.requestBodies)}
741
+
742
+ // HOOKS
743
+ ${generateQueryHooks(specs.paths, operationIds, specs.components, headerFilters)}
737
744
  `;
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
745
  return output;
753
746
  };
754
747
  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,67 +419,58 @@ 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
+ // USE AS EXAMPLE
467
+ type ${componentName}Variables = {
468
+ ${queryParamsType}
484
469
  }
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'>) => {
470
+
471
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
472
+ use${componentName}Query.queryKey = (params: ${componentName}Variables ): QueryKey => [...use${componentName}Query.baseKey(), params];
473
+ use${componentName}Query.fetch = async (props: ${componentName}Variables) => {
491
474
  const params = queryString.stringify({${queryParams
492
475
  .map((param) => `${param.name}: props.${param.name}`)
493
476
  .join(',')}});
@@ -495,37 +478,20 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
495
478
  return result.data;
496
479
  }
497
480
 
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];
481
+ export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}Variables & { options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>}) {
482
+ return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
483
+ { enabled: !!props${queryParams.map((param) => `["${param.name}"]`).join(' && !!props')}, ...options }
484
+ );}
501
485
 
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
- )};`;
486
+ export function use${componentName}Mutation<T = ${genericsTypes}>(props?: { options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}Variables, T>}) {
487
+ return useMutation(async (data) => use${componentName}Query.fetch(data),
488
+ props?.options
489
+ )};
490
+ `;
520
491
  }
521
492
  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
- );}
493
+ output += `
494
+ type ${componentName}QueryVariables = ${requestBodyComponent};
529
495
 
530
496
  use${componentName}Query.fetch = async (body: Omit<${componentName}QueryProps, 'options'>) => {
531
497
  const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
@@ -533,46 +499,49 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
533
499
  }
534
500
 
535
501
  use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
536
-
537
502
  use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
538
503
 
539
- `;
540
- output += `type ${componentName}MutationVariables = ${requestBodyComponent};
541
- interface ${componentName}MutationProps<T> {
504
+ type ${componentName}QueryProps<T = ${genericsTypes}> = ${componentName}QueryVariables & {
505
+ options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
506
+ }
507
+ export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...body }: ${componentName}QueryProps<T>) {
508
+ return useQuery(use${componentName}Query.queryKey(body), async () => use${componentName}Query.fetch(body), options
509
+ );}
510
+
511
+
512
+
513
+ type ${componentName}MutationVariables = ${requestBodyComponent};
514
+ type ${componentName}MutationProps<T> = {
542
515
  options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
543
516
  }
544
517
  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
- },
518
+ return useMutation(async (body) => use${componentName}Query.fetch(body),
549
519
  props?.options
550
520
  )};`;
551
521
  }
552
522
  if (requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
553
- output += `interface ${componentName}QueryProps<T = ${genericsTypes}> extends ${requestBodyComponent
523
+ output += `
524
+ type ${componentName}QueryProps<T = ${genericsTypes}> = ${requestBodyComponent
554
525
  .replace('{', '')
555
- .replace('}', '')} {
526
+ .replace('}', '')} & {
556
527
  ${paramsTypes};
557
528
  options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
558
529
  }
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
530
 
563
531
  use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'>) => {
564
532
  const {${paramsInPath.join(', ')}, ...body} = props
565
533
  const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
566
534
  return result.data
567
535
  }
568
-
569
536
  use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
570
-
571
537
  use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
572
538
 
573
- `;
574
- output += `type ${componentName}MutationVariables = {${paramsTypes}} & ${requestBodyComponent}
575
- interface ${componentName}MutationProps<T> {
539
+ export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
540
+ return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props), { enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
541
+ );}
542
+
543
+ type ${componentName}MutationVariables = {${paramsTypes}} & ${requestBodyComponent}
544
+ type ${componentName}MutationProps<T> = {
576
545
  options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
577
546
  }
578
547
  export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
@@ -594,9 +563,21 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
594
563
  }
595
564
  if (!requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
596
565
  output += `
597
- // HELLO
598
- type ${componentName}HeaderVariables = {${headerParam}};
599
- type ${componentName}QueryProps<T = ${genericsTypes}> = ${componentName}HeaderVariables & {
566
+ // DONE
567
+ type ${componentName}Variables = {
568
+ ${headerParam}
569
+ };
570
+
571
+ use${componentName}Query.fetch = async (headers: ${componentName}Variables) => {
572
+ const result = await api.${verb}<${genericsTypes}>(\`${route}\`, {headers: headers});
573
+ return result.data;
574
+ }
575
+
576
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
577
+
578
+ use${componentName}Query.queryKey = (params: ${componentName}Variables ): QueryKey => [...use${componentName}Query.baseKey(), params];
579
+
580
+ type ${componentName}QueryProps<T = ${genericsTypes}> = ${componentName}Variables & {
600
581
  options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
601
582
  }
602
583
  export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
@@ -604,95 +585,89 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
604
585
  { enabled: !!props${headerParams.map((param) => `["${param.name}"]`).join(' && !!props')}, ...options }
605
586
  );}
606
587
 
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
588
 
614
- use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
615
589
 
616
590
  type ${componentName}MutationProps<T> = {
617
- options?: UseMutationOptions<${genericsTypes}, AxiosError, void, T>
591
+ options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}Variables, T>
618
592
  }
619
593
  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
- },
594
+ return useMutation(async (data) => use${componentName}Query.fetch(data),
624
595
  props?.options
625
596
  )};`;
626
597
  }
627
598
  if (!requestBodyComponent && !paramsInPath.length && queryParam && headerParam) {
628
- output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
599
+ output += `
600
+ // DONE
601
+ type ${componentName}Variables = {
602
+ ${headerParam}
629
603
  ${queryParamsType};
604
+ };
605
+
606
+ use${componentName}Query.fetch = async (data: ${componentName}Variables) => {
607
+ const params = queryString.stringify({
608
+ ${queryParams.map((param) => `${param.name}: data.${param.name}`).join(',')}
609
+ });
610
+ const headers = {
611
+ ${headerParams.map((param) => `"${param.name}": data["${param.name}"]`).join(',')}
612
+ }
613
+ // HIHI
614
+ const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`, {headers})
615
+ return result.data;
616
+ }
617
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
618
+ use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
619
+
620
+ type ${componentName}QueryProps<T = ${genericsTypes}> = ${componentName}Variables & {
630
621
  options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
631
622
  }
632
623
  export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
633
624
  return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
634
- { enabled: !!props.${queryParams.map((param) => param.name).join(' && !!props.')}, ...options }
625
+ { enabled: !!props${[...queryParams, ...headerParams]
626
+ .map((param) => `["${param.name}"]`)
627
+ .join(' && !!props')}, ...options }
635
628
  );}
636
629
 
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>
630
+ type ${componentName}MutationProps<T> = {
631
+ options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}Variables, T>
654
632
  }
655
633
 
656
634
  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
- },
635
+ return useMutation(async (data) => use${componentName}Query.fetch(data),
664
636
  props?.options
665
637
  )};`;
666
638
  }
667
639
  if (requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
668
640
  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
- );}
641
+ // HEHEHEHEHE
642
+ type ${componentName}Variables = ${requestBodyComponent} & {
643
+ ${headerParam}
644
+ };
676
645
 
677
- use${componentName}Query.fetch = async (body: Omit<${componentName}QueryProps, 'options'>) => {
678
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
646
+ use${componentName}Query.fetch = async (body: ${componentName}Variables) => {
647
+ const headers = {
648
+ ${headerParams.map((param) => `"${param.name}": body["${param.name}"]`).join(',')}
649
+ }
650
+ const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body, {headers})
679
651
  return result.data
680
652
  }
681
-
682
653
  use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
654
+ use${componentName}Query.queryKey = (params: ${componentName}Variables ): QueryKey => [...use${componentName}Query.baseKey(), params];
655
+
656
+ type ${componentName}QueryProps<T = ${genericsTypes}> = ${componentName}Variables & {
657
+ options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
658
+ }
659
+ export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...body }: ${componentName}QueryProps<T>) {
660
+ return useQuery(use${componentName}Query.queryKey(body), async () => use${componentName}Query.fetch(body),{ enabled: !!body${headerParams
661
+ .map((param) => `["${param.name}"]`)
662
+ .join(' && !!props')}, ...options }
663
+ );}
683
664
 
684
- use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
685
-
686
- type ${componentName}MutationVariables = ${requestBodyComponent};
687
665
 
688
- interface ${componentName}MutationProps<T> {
689
- options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
666
+ type ${componentName}MutationProps<T> = {
667
+ options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}Variables, T>
690
668
  }
691
669
  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
- },
670
+ return useMutation(async (body) => use${componentName}Query.fetch(body),
696
671
  props?.options
697
672
  )};`;
698
673
  }
@@ -701,32 +676,50 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
701
676
  }
702
677
  return output;
703
678
  };
679
+ const generateQueryHooks = (paths, operationIds, schemasComponents, headerFilters) => {
680
+ let output = '';
681
+ Object.entries(paths).forEach(([route, verbs]) => {
682
+ Object.entries(verbs).forEach(([verb, operation]) => {
683
+ if (['get', 'post', 'patch', 'put', 'delete'].includes(verb) && !operation.deprecated) {
684
+ output += generateRestfulComponent({
685
+ operation,
686
+ verb,
687
+ route,
688
+ operationIds,
689
+ parameters: verbs.parameters,
690
+ schemasComponents,
691
+ headerFilters,
692
+ });
693
+ }
694
+ });
695
+ });
696
+ return output;
697
+ };
704
698
  /**
705
699
  * Main entry of the generator. Generate react-query component from openAPI.
706
700
  */
707
- export const importOpenApi = async ({ data, format, apiDir, }) => {
701
+ export const importOpenApi = async ({ data, format, apiDir, headerFilters = [], }) => {
708
702
  const operationIds = [];
709
703
  let specs = await importSpecs(data, format);
710
704
  resolveDiscriminator(specs);
711
- let output = `
705
+ let output = '';
706
+ output = `
712
707
  import { useQuery, useMutation, UseQueryOptions, UseMutationOptions, QueryKey } from 'react-query';
713
708
  import queryString from 'query-string';
714
709
  import {AxiosError} from 'axios';
715
710
  import { api } from '${apiDir}';
711
+
712
+ // SCEHMAS
713
+ ${generateSchemasDefinition(specs.components?.schemas)}
714
+
715
+ // RESPONSES
716
+ ${generateResponsesDefinition(specs.components?.responses)}
717
+
718
+ // REQUEST BODIES
719
+ ${generateRequestBodiesDefinition(specs.components?.requestBodies)}
720
+
721
+ // HOOKS
722
+ ${generateQueryHooks(specs.paths, operationIds, specs.components, headerFilters)}
716
723
  `;
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
724
  return output;
732
725
  };
@@ -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.12",
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
  }