react-query-lightbase-codegen 0.0.10 → 0.0.13

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.
@@ -7,10 +7,10 @@ exports.importSpecs = void 0;
7
7
  const chalk_1 = __importDefault(require("chalk"));
8
8
  const fs_1 = require("fs");
9
9
  const path_1 = require("path");
10
- const import_open_api_js_1 = require("./import-open-api.js");
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_js_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
  }
@@ -1,9 +1,11 @@
1
- import _case from 'case';
2
- import _ from 'lodash';
3
- const { pascal } = _case;
4
- const { uniq, get, groupBy, isEmpty, set } = _;
1
+ import { pascal } from 'case';
2
+ import get from 'lodash/get';
3
+ import groupBy from 'lodash/groupBy';
4
+ import isEmpty from 'lodash/isEmpty';
5
+ import set from 'lodash/set';
6
+ import uniq from 'lodash/uniq';
5
7
  import swagger2openapi from 'swagger2openapi';
6
- import yaml from 'js-yaml';
8
+ const yaml = require('js-yaml');
7
9
  const IdentifierRegexp = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
8
10
  /**
9
11
  * Import and parse the openapi spec from a yaml/json
@@ -285,12 +287,12 @@ export const formatDescription = (description, tabSize = 0) => description
285
287
  ? `/**\n${description
286
288
  .split('\n')
287
289
  .map((i) => `${' '.repeat(tabSize)} * ${i}`)
288
- .join('\n')}\n${' '.repeat(tabSize)} */\n${' '.repeat(tabSize)}`
290
+ .join('\n')}\n${' '.repeat(tabSize)} */${' '.repeat(tabSize)}`
289
291
  : '';
290
292
  /**
291
293
  * Generate a react-query component from openapi operation specs
292
294
  */
293
- export const generateRestfulComponent = (operation, verb, route, operationIds, parameters = [], schemasComponents) => {
295
+ export const generateRestfulComponent = ({ operation, verb, route, operationIds, parameters, schemasComponents, headerFilters, }) => {
294
296
  const { operationId = route.replace('/', '') } = operation;
295
297
  if (operationId === '*') {
296
298
  throw new Error(`Invalid operationId/Route set for ${verb} ${route}`);
@@ -308,7 +310,7 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
308
310
  const requestBodyTypes = getResReqTypes([['body', operation.requestBody]]);
309
311
  const needAResponseComponent = true;
310
312
  const paramsInPath = getParamsInPath(route).filter((param) => !(verb === 'delete' && param === lastParamInTheRoute));
311
- 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) => {
312
314
  if (isReference(p)) {
313
315
  return get(schemasComponents, p.$ref.replace('#/components/', '').replace('/', '.'));
314
316
  }
@@ -316,6 +318,7 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
316
318
  return p;
317
319
  }
318
320
  }), 'in');
321
+ const headerParams = header.filter((p) => !headerFilters?.includes(p.name));
319
322
  const paramsTypes = paramsInPath
320
323
  .map((p) => {
321
324
  try {
@@ -371,52 +374,43 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
371
374
  const headerParam = headerType && headerType !== 'void' ? `${headerType};` : '';
372
375
  const queryParam = queryParamsType && queryParamsType !== 'void' ? `${queryParamsType}` : '';
373
376
  const requestBodyComponent = requestBodyTypes && requestBodyTypes !== 'void' ? `${requestBodyTypes}` : '';
374
- console.log(headerParam);
375
377
  // QUERIES
376
378
  if (!requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
377
- output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
378
- ${paramsTypes};
379
- options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
379
+ output += `
380
+ type ${componentName}Variables = {
381
+ ${paramsTypes}
380
382
  }
381
- export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
382
- return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
383
- { enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
384
- );}
385
383
 
386
384
  use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'> ) => {
387
385
  const result = await api.${verb}<${genericsTypes}>(\`${route.replace(/\{/g, '{props.')}\`);
388
386
  return result.data;
389
387
  }
390
-
391
388
  use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
389
+ use${componentName}Query.queryKey = (params: ${componentName}Variables ): QueryKey => [...use${componentName}Query.baseKey(), params];
392
390
 
393
- use${componentName}Query.queryKey = (params: {${paramsTypes}} ): QueryKey => [...use${componentName}Query.baseKey(), params];
394
-
395
- `;
396
- output += `interface ${componentName}MutationVariables {
397
- ${paramsTypes}
391
+ type ${componentName}QueryProps<T = ${genericsTypes}> = ${componentName}Variables & {
392
+ options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
398
393
  }
399
- 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> = {
400
400
  options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
401
401
  }
402
402
  export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
403
- return useMutation(async ({${paramsInPath.join(', ')}}) => {
404
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`)
405
- return result.data
406
- },
403
+ return useMutation(async (data) => use${componentName}Query.fetch(data),
407
404
  props?.options
408
405
  )};`;
409
406
  }
410
407
  if (!requestBodyComponent && paramsInPath.length && queryParam && !headerParam) {
411
- output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
412
- ${paramsTypes};
408
+ output += `
409
+ type ${componentName}Variables = {
410
+ ${paramsTypes}
413
411
  ${queryParamsType};
414
- options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
415
412
  }
416
- export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
417
- return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props), { enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
418
- );}
419
-
413
+
420
414
  use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'>) => {
421
415
  const {${paramsInPath.join(', ')}, ...queryParams} = props
422
416
  const params = queryString.stringify(queryParams);
@@ -425,67 +419,58 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
425
419
  }
426
420
 
427
421
  use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
428
-
429
422
  use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'>): QueryKey => [...use${componentName}Query.baseKey(), params];
430
-
431
- `;
432
- output += `interface ${componentName}MutationVariables {
433
- ${paramsTypes}
434
- ${queryParamsType}
423
+
424
+
425
+ type ${componentName}QueryProps<T = ${genericsTypes}> ${componentName}Variables & {
426
+ options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
435
427
  }
436
- interface ${componentName}MutationProps<T> {
437
- 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>
438
434
  }
439
435
  export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
440
- return useMutation(async (data) => {
441
- const {${paramsInPath.join(', ')}, ...queryParams} = data
442
- const params = queryString.stringify(queryParams);
443
- const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
444
- return result.data
445
- },
436
+ return useMutation(async (data) => use${componentName}Query.fetch(data),
446
437
  props?.options
447
438
  )};`;
448
439
  }
449
440
  if (!requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
450
- 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}> = {
451
450
  options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
452
451
  }
453
452
  export function use${componentName}Query<T = ${genericsTypes}>(props?: ${componentName}QueryProps<T>) {
454
453
  return useQuery(use${componentName}Query.queryKey(), use${componentName}Query.fetch, props?.options
455
- );}
456
-
457
- use${componentName}Query.fetch = async () => {
458
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`);
459
- return result.data;
460
- }
454
+ );}
461
455
 
462
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
463
-
464
- use${componentName}Query.queryKey = (): QueryKey => use${componentName}Query.baseKey()
465
-
466
- `;
467
- output += `interface ${componentName}MutationProps<T> {
456
+ type ${componentName}MutationProps<T> = {
468
457
  options?: UseMutationOptions<${genericsTypes}, AxiosError, void, T>
469
458
  }
470
459
  export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
471
- return useMutation(async () => {
472
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`);
473
- return result.data;
474
- },
460
+ return useMutation(async () => use${componentName}Query.fetch(),
475
461
  props?.options
476
462
  )};`;
477
463
  }
478
464
  if (!requestBodyComponent && !paramsInPath.length && queryParam && !headerParam) {
479
- output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
480
- ${queryParamsType};
481
- options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
465
+ output += `
466
+ // USE AS EXAMPLE
467
+ type ${componentName}Variables = {
468
+ ${queryParamsType}
482
469
  }
483
- export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
484
- return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
485
- { enabled: !!props.${queryParams.map((param) => param.name).join(' && !!props.')}, ...options }
486
- );}
487
-
488
- 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) => {
489
474
  const params = queryString.stringify({${queryParams
490
475
  .map((param) => `${param.name}: props.${param.name}`)
491
476
  .join(',')}});
@@ -493,37 +478,20 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
493
478
  return result.data;
494
479
  }
495
480
 
496
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
497
-
498
- 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
+ );}
499
485
 
500
- `;
501
- output += `interface ${componentName}MutationVariables {
502
- ${queryParamsType}
503
- }
504
- interface ${componentName}MutationProps<T> {
505
- options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
506
- }
507
-
508
- export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
509
- return useMutation(async (data) => {
510
- const params = queryString.stringify({${queryParams
511
- .map((param) => `${param.name}: data.${param.name}`)
512
- .join(',')}});
513
- const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
514
- return result.data;
515
- },
516
- props?.options
517
- )};`;
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
+ `;
518
491
  }
519
492
  if (requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
520
- output += `type ${componentName}QueryVariables = ${requestBodyComponent};
521
- interface ${componentName}QueryProps<T = ${genericsTypes}> extends ${componentName}QueryVariables {
522
- options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
523
- }
524
- export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...body }: ${componentName}QueryProps<T>) {
525
- return useQuery(use${componentName}Query.queryKey(body), async () => use${componentName}Query.fetch(body), options
526
- );}
493
+ output += `
494
+ type ${componentName}QueryVariables = ${requestBodyComponent};
527
495
 
528
496
  use${componentName}Query.fetch = async (body: Omit<${componentName}QueryProps, 'options'>) => {
529
497
  const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
@@ -531,46 +499,49 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
531
499
  }
532
500
 
533
501
  use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
534
-
535
502
  use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
536
503
 
537
- `;
538
- output += `type ${componentName}MutationVariables = ${requestBodyComponent};
539
- 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> = {
540
515
  options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
541
516
  }
542
517
  export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
543
- return useMutation(async (body) => {
544
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
545
- return result.data
546
- },
518
+ return useMutation(async (body) => use${componentName}Query.fetch(body),
547
519
  props?.options
548
520
  )};`;
549
521
  }
550
522
  if (requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
551
- output += `interface ${componentName}QueryProps<T = ${genericsTypes}> extends ${requestBodyComponent
523
+ output += `
524
+ type ${componentName}QueryProps<T = ${genericsTypes}> = ${requestBodyComponent
552
525
  .replace('{', '')
553
- .replace('}', '')} {
526
+ .replace('}', '')} & {
554
527
  ${paramsTypes};
555
528
  options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
556
529
  }
557
- export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
558
- return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props), { enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
559
- );}
560
530
 
561
531
  use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'>) => {
562
532
  const {${paramsInPath.join(', ')}, ...body} = props
563
533
  const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
564
534
  return result.data
565
535
  }
566
-
567
536
  use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
568
-
569
537
  use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
570
538
 
571
- `;
572
- output += `type ${componentName}MutationVariables = {${paramsTypes}} & ${requestBodyComponent}
573
- 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> = {
574
545
  options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
575
546
  }
576
547
  export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
@@ -592,9 +563,21 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
592
563
  }
593
564
  if (!requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
594
565
  output += `
595
- // HELLO
596
- type ${componentName}HeaderVariables = {${headerParam}};
597
- 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 & {
598
581
  options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
599
582
  }
600
583
  export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
@@ -602,95 +585,89 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
602
585
  { enabled: !!props${headerParams.map((param) => `["${param.name}"]`).join(' && !!props')}, ...options }
603
586
  );}
604
587
 
605
- use${componentName}Query.fetch = async (headers: ${componentName}HeaderVariables) => {
606
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`, {headers: headers});
607
- return result.data;
608
- }
609
-
610
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
611
588
 
612
- use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
613
589
 
614
590
  type ${componentName}MutationProps<T> = {
615
- options?: UseMutationOptions<${genericsTypes}, AxiosError, void, T>
591
+ options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}Variables, T>
616
592
  }
617
593
  export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
618
- return useMutation(async () => {
619
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`);
620
- return result.data;
621
- },
594
+ return useMutation(async (data) => use${componentName}Query.fetch(data),
622
595
  props?.options
623
596
  )};`;
624
597
  }
625
598
  if (!requestBodyComponent && !paramsInPath.length && queryParam && headerParam) {
626
- output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
599
+ output += `
600
+ // DONE
601
+ type ${componentName}Variables = {
602
+ ${headerParam}
627
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 & {
628
621
  options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
629
622
  }
630
623
  export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
631
624
  return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
632
- { enabled: !!props.${queryParams.map((param) => param.name).join(' && !!props.')}, ...options }
625
+ { enabled: !!props${[...queryParams, ...headerParams]
626
+ .map((param) => `["${param.name}"]`)
627
+ .join(' && !!props')}, ...options }
633
628
  );}
634
629
 
635
- use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'>) => {
636
- const params = queryString.stringify({${queryParams
637
- .map((param) => `${param.name}: props.${param.name}`)
638
- .join(',')}});
639
- const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
640
- return result.data;
641
- }
642
-
643
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
644
-
645
- use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
646
-
647
- interface ${componentName}MutationVariables {
648
- ${queryParamsType}
649
- }
650
- interface ${componentName}MutationProps<T> {
651
- options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
630
+ type ${componentName}MutationProps<T> = {
631
+ options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}Variables, T>
652
632
  }
653
633
 
654
634
  export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
655
- return useMutation(async (data) => {
656
- const params = queryString.stringify({${queryParams
657
- .map((param) => `${param.name}: data.${param.name}`)
658
- .join(',')}});
659
- const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
660
- return result.data;
661
- },
635
+ return useMutation(async (data) => use${componentName}Query.fetch(data),
662
636
  props?.options
663
637
  )};`;
664
638
  }
665
639
  if (requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
666
640
  output += `
667
- type ${componentName}QueryVariables = ${requestBodyComponent};
668
- interface ${componentName}QueryProps<T = ${genericsTypes}> extends ${componentName}QueryVariables {
669
- options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
670
- }
671
- export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...body }: ${componentName}QueryProps<T>) {
672
- return useQuery(use${componentName}Query.queryKey(body), async () => use${componentName}Query.fetch(body), options
673
- );}
641
+ // HEHEHEHEHE
642
+ type ${componentName}Variables = ${requestBodyComponent} & {
643
+ ${headerParam}
644
+ };
674
645
 
675
- use${componentName}Query.fetch = async (body: Omit<${componentName}QueryProps, 'options'>) => {
676
- 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})
677
651
  return result.data
678
652
  }
679
-
680
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
+ );}
681
664
 
682
- use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
683
-
684
- type ${componentName}MutationVariables = ${requestBodyComponent};
685
665
 
686
- interface ${componentName}MutationProps<T> {
687
- options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
666
+ type ${componentName}MutationProps<T> = {
667
+ options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}Variables, T>
688
668
  }
689
669
  export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
690
- return useMutation(async (body) => {
691
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
692
- return result.data
693
- },
670
+ return useMutation(async (body) => use${componentName}Query.fetch(body),
694
671
  props?.options
695
672
  )};`;
696
673
  }
@@ -699,32 +676,50 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
699
676
  }
700
677
  return output;
701
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
+ };
702
698
  /**
703
699
  * Main entry of the generator. Generate react-query component from openAPI.
704
700
  */
705
- export const importOpenApi = async ({ data, format, apiDir, }) => {
701
+ export const importOpenApi = async ({ data, format, apiDir, headerFilters = [], }) => {
706
702
  const operationIds = [];
707
703
  let specs = await importSpecs(data, format);
708
704
  resolveDiscriminator(specs);
709
- let output = `
705
+ let output = '';
706
+ output = `
710
707
  import { useQuery, useMutation, UseQueryOptions, UseMutationOptions, QueryKey } from 'react-query';
711
708
  import queryString from 'query-string';
712
709
  import {AxiosError} from 'axios';
713
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)}
714
723
  `;
715
- output += '\n\n// SCEHMAS\n';
716
- output += generateSchemasDefinition(specs.components && specs.components.schemas);
717
- output += '\n\n// RESPONSES\n';
718
- output += generateResponsesDefinition(specs.components && specs.components.responses);
719
- output += '\n\n// REQUEST BODIES\n';
720
- output += generateRequestBodiesDefinition(specs.components && specs.components.requestBodies);
721
- output += '\n\n// HOOKS\n';
722
- Object.entries(specs.paths).forEach(([route, verbs]) => {
723
- Object.entries(verbs).forEach(([verb, operation]) => {
724
- if (['get', 'post', 'patch', 'put', 'delete'].includes(verb) && !operation.deprecated) {
725
- output += generateRestfulComponent(operation, verb, route, operationIds, verbs.parameters, specs.components);
726
- }
727
- });
728
- });
729
724
  return output;
730
725
  };
@@ -1,10 +1,10 @@
1
1
  import chalk from 'chalk';
2
2
  import { readFileSync, writeFileSync, readdir } from 'fs';
3
3
  import { join, parse } from 'path';
4
- import { importOpenApi } from './import-open-api.js';
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
  }