react-query-lightbase-codegen 1.1.1 → 1.1.4
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.
- package/dist/convertSwaggerFile.d.ts +5 -0
- package/{lib/esm → dist}/convertSwaggerFile.js +1 -0
- package/dist/convertSwaggerFile.js.map +1 -0
- package/dist/generateHooks.d.ts +25 -0
- package/dist/generateHooks.js +395 -0
- package/dist/generateHooks.js.map +1 -0
- package/dist/generateImports.d.ts +7 -0
- package/dist/generateImports.js +28 -0
- package/dist/generateImports.js.map +1 -0
- package/dist/generateSchemas.d.ts +7 -0
- package/{lib/esm → dist}/generateSchemas.js +7 -7
- package/dist/generateSchemas.js.map +1 -0
- package/dist/importSpecs.d.ts +15 -0
- package/dist/importSpecs.js +90 -0
- package/dist/importSpecs.js.map +1 -0
- package/{lib/esm/index.js → dist/index.d.ts} +0 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -0
- package/dist/utils.d.ts +24 -0
- package/{lib/esm → dist}/utils.js +22 -18
- package/dist/utils.js.map +1 -0
- package/package.json +3 -3
- package/src/generateHooks.ts +5 -2
- package/lib/cjs/convertSwaggerFile.js +0 -32
- package/lib/cjs/generateHooks.js +0 -368
- package/lib/cjs/generateImports.js +0 -26
- package/lib/cjs/generateSchemas.js +0 -104
- package/lib/cjs/importSpecs.js +0 -46
- package/lib/cjs/index.js +0 -7
- package/lib/cjs/utils.js +0 -165
- package/lib/esm/generateHooks.js +0 -360
- package/lib/esm/generateImports.js +0 -22
- package/lib/esm/importSpecs.js +0 -39
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import Case from 'case';
|
|
2
|
+
import chalk from 'chalk';
|
|
3
|
+
import { readFileSync, writeFileSync, readdir, mkdirSync } from 'fs';
|
|
4
|
+
import { join, parse } from 'path';
|
|
5
|
+
import { convertSwaggerFile } from './convertSwaggerFile.js';
|
|
6
|
+
import { createHook } from './generateHooks.js';
|
|
7
|
+
import { generateImports } from './generateImports.js';
|
|
8
|
+
import { generateSchemas } from './generateSchemas.js';
|
|
9
|
+
import execa from 'execa';
|
|
10
|
+
export function importSpecs({ sourceDirectory, exportDirectory, apiDirectory, queryClientDir, headerFilters, overrides, }) {
|
|
11
|
+
readdir(sourceDirectory, async (err, filenames) => {
|
|
12
|
+
if (err) {
|
|
13
|
+
console.log(err);
|
|
14
|
+
throw err;
|
|
15
|
+
}
|
|
16
|
+
filenames.forEach(async (filename) => {
|
|
17
|
+
try {
|
|
18
|
+
const data = readFileSync(join(process.cwd(), sourceDirectory + '/' + filename), 'utf-8');
|
|
19
|
+
const { ext } = parse(sourceDirectory + '/' + filename);
|
|
20
|
+
const format = ['.yaml', '.yml'].includes(ext.toLowerCase()) ? 'yaml' : 'json';
|
|
21
|
+
let spec = await convertSwaggerFile(data, format);
|
|
22
|
+
const formattedFileName = Case.camel(`useQueries, ${filename.split('.')[0]}`);
|
|
23
|
+
const schemaName = `${formattedFileName}.schema`;
|
|
24
|
+
const hooksName = `${formattedFileName}`;
|
|
25
|
+
const name = filename.split('.')[0];
|
|
26
|
+
mkdirSync(join(process.cwd(), `${exportDirectory}/${name}`), { recursive: true });
|
|
27
|
+
const operationIds = [];
|
|
28
|
+
let hooks = '';
|
|
29
|
+
let schemaImportsArray = [];
|
|
30
|
+
let collectedQueryImports = [];
|
|
31
|
+
Object.entries(spec.paths).forEach(([route, verbs]) => {
|
|
32
|
+
Object.entries(verbs).forEach(([verb, operation]) => {
|
|
33
|
+
if (['get', 'post', 'patch', 'put', 'delete'].includes(verb) && !operation.deprecated) {
|
|
34
|
+
const { implementation, imports, queryImports } = createHook({
|
|
35
|
+
operation,
|
|
36
|
+
verb,
|
|
37
|
+
route: (spec.basePath || '') + route,
|
|
38
|
+
operationIds,
|
|
39
|
+
parameters: verbs.parameters,
|
|
40
|
+
schemasComponents: spec.components,
|
|
41
|
+
headerFilters,
|
|
42
|
+
overrides,
|
|
43
|
+
});
|
|
44
|
+
hooks += implementation;
|
|
45
|
+
imports.forEach((element) => {
|
|
46
|
+
const formattedImport = element.replace('[]', '');
|
|
47
|
+
if (!schemaImportsArray.includes(formattedImport) &&
|
|
48
|
+
element !== 'void' &&
|
|
49
|
+
element !== 'string' &&
|
|
50
|
+
!element.includes('{')) {
|
|
51
|
+
schemaImportsArray.push(formattedImport);
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
queryImports.forEach((element) => {
|
|
55
|
+
if (!schemaImportsArray.includes(element)) {
|
|
56
|
+
collectedQueryImports.push(element);
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
const imports = generateImports({
|
|
63
|
+
apiDirectory,
|
|
64
|
+
queryClientDir,
|
|
65
|
+
schemaName,
|
|
66
|
+
schemaImports: schemaImportsArray,
|
|
67
|
+
queryImports: collectedQueryImports,
|
|
68
|
+
});
|
|
69
|
+
writeFileSync(join(process.cwd(), `${exportDirectory}/${name}/${hooksName}.tsx`), imports + hooks);
|
|
70
|
+
writeFileSync(join(process.cwd(), `${exportDirectory}/${name}/${schemaName}.tsx`), generateSchemas({ spec }));
|
|
71
|
+
console.log(chalk.green(`🎉 [${filename}] Your OpenAPI spec has been converted into react query hooks`));
|
|
72
|
+
try {
|
|
73
|
+
execa.sync('prettier', ['--write', `./${exportDirectory}/${name}/*.tsx`]);
|
|
74
|
+
console.log(chalk.blue(`⚙️ Running prettier`));
|
|
75
|
+
}
|
|
76
|
+
catch (e) {
|
|
77
|
+
console.log(chalk.yellow(`⚠️ Prettier not found`));
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
if (error.code === 'EISDIR') {
|
|
82
|
+
console.log(chalk.red('nested folder structure not supported'));
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
console.log(chalk.red(`[${filename}]:`), chalk.red(error));
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
//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AC"}
|
package/dist/utils.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { ReferenceObject, RequestBodyObject, ResponseObject, SchemaObject } from 'openapi3-ts';
|
|
2
|
+
export declare const getDocs: (data: ReferenceObject | {
|
|
3
|
+
description?: string;
|
|
4
|
+
}) => string;
|
|
5
|
+
/**
|
|
6
|
+
* Discriminator helper for `ReferenceObject`
|
|
7
|
+
*/
|
|
8
|
+
export declare const isReference: (property: any) => property is ReferenceObject;
|
|
9
|
+
/**
|
|
10
|
+
* Return the typescript equivalent of open-api data type
|
|
11
|
+
*/
|
|
12
|
+
export declare const getScalar: (item: SchemaObject) => string;
|
|
13
|
+
/**
|
|
14
|
+
* Resolve the value of a schema object to a proper type definition.
|
|
15
|
+
*/
|
|
16
|
+
export declare const resolveValue: (schema: SchemaObject) => string;
|
|
17
|
+
/**
|
|
18
|
+
* Format a description to code documentation.
|
|
19
|
+
*/
|
|
20
|
+
export declare const formatDescription: (description?: string) => string;
|
|
21
|
+
/**
|
|
22
|
+
* Extract responses / request types from open-api specs
|
|
23
|
+
*/
|
|
24
|
+
export declare const getResReqTypes: (responsesOrRequests: Array<[string, ResponseObject | ReferenceObject | RequestBodyObject]>) => string;
|
|
@@ -122,9 +122,10 @@ export const resolveValue = (schema) => isReference(schema) ? getRef(schema.$ref
|
|
|
122
122
|
* Format a description to code documentation.
|
|
123
123
|
*/
|
|
124
124
|
export const formatDescription = (description) => {
|
|
125
|
-
if (!description)
|
|
125
|
+
if (!description) {
|
|
126
126
|
return '';
|
|
127
|
-
|
|
127
|
+
}
|
|
128
|
+
return `\n/**\n${description
|
|
128
129
|
.split('\n')
|
|
129
130
|
.map((i) => `* ${i}`)
|
|
130
131
|
.join('\n')}\n */`;
|
|
@@ -132,22 +133,25 @@ export const formatDescription = (description) => {
|
|
|
132
133
|
/**
|
|
133
134
|
* Extract responses / request types from open-api specs
|
|
134
135
|
*/
|
|
135
|
-
export const getResReqTypes = (responsesOrRequests) =>
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
contentType.startsWith('application/
|
|
146
|
-
|
|
147
|
-
|
|
136
|
+
export const getResReqTypes = (responsesOrRequests) => {
|
|
137
|
+
return uniq(responsesOrRequests.map(([_, res]) => {
|
|
138
|
+
if (!res) {
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
if (isReference(res)) {
|
|
142
|
+
return getRef(res.$ref);
|
|
143
|
+
}
|
|
144
|
+
if (res.content) {
|
|
145
|
+
for (let contentType of Object.keys(res.content)) {
|
|
146
|
+
if (contentType.startsWith('application/json') ||
|
|
147
|
+
contentType.startsWith('application/octet-stream')) {
|
|
148
|
+
const schema = res.content[contentType].schema;
|
|
149
|
+
return resolveValue(schema);
|
|
150
|
+
}
|
|
148
151
|
}
|
|
152
|
+
return;
|
|
149
153
|
}
|
|
150
154
|
return;
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
|
|
155
|
+
})).join(' | ');
|
|
156
|
+
};
|
|
157
|
+
//# sourceMappingURL=utils.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAC5B,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC;AACjC,OAAO,OAAO,MAAM,MAAM,CAAC;AAE3B,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;AAI3B,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,IAAgD,EAAE,EAAE,CAC1E,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,iBAAiB,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;AAC/D;;GAEG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,C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IAAI,CAAC,GAAG,EAAE;YACR,OAAO;SACR;QAED,IAAI,WAAW,CAAC,GAAG,CAAC,EAAE;YACpB,OAAO,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;SACzB;QAED,IAAI,GAAG,CAAC,OAAO,EAAE;YACf,KAAK,IAAI,WAAW,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE;gBAChD,IACE,WAAW,CAAC,UAAU,CAAC,kBAAkB,CAAC;oBAC1C,WAAW,CAAC,UAAU,CAAC,0BAA0B,CAAC,EAClD;oBACA,MAAM,MAAM,GAAG,GAAG,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,MAAO,CAAC;oBAEhD,OAAO,YAAY,CAAC,MAAM,CAAC,CAAC;iBAC7B;aACF;YACD,OAAO;SACR;QAED,OAAO;IACT,CAAC,CAAC,CACH,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAChB,CAAC,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "react-query-lightbase-codegen",
|
|
3
3
|
"description": "Fully typed react query code generation tool based on openApi specifications",
|
|
4
|
-
"version": "1.1.
|
|
4
|
+
"version": "1.1.4",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
7
|
-
"exports": "./
|
|
7
|
+
"exports": "./dist/index.js",
|
|
8
8
|
"files": [
|
|
9
9
|
"src",
|
|
10
|
-
"
|
|
10
|
+
"dist"
|
|
11
11
|
],
|
|
12
12
|
"keywords": [
|
|
13
13
|
"rest",
|
package/src/generateHooks.ts
CHANGED
|
@@ -200,12 +200,15 @@ export const createHook = ({
|
|
|
200
200
|
? `use${componentName}Query.baseKey()`
|
|
201
201
|
: `[...use${componentName}Query.baseKey(), params]`;
|
|
202
202
|
|
|
203
|
+
const props = emptyParams ? `props?` : `{ options = {}, ...params }`;
|
|
204
|
+
const options = emptyParams ? `...props?.options:` : `...options`;
|
|
205
|
+
|
|
203
206
|
const createQuery = () => `
|
|
204
207
|
type ${componentName}QueryProps<T = ${responseTypes}> = ${queryParamType} {
|
|
205
208
|
options?: UseQueryOptions<${responseTypes}, AxiosError, T, any>
|
|
206
209
|
}
|
|
207
|
-
export function use${componentName}Query<T = ${responseTypes}>({
|
|
208
|
-
return useQuery(use${componentName}Query.queryKey(${key}), async () => ${fetchName}(${key}), { enabled: ${enabledParam},
|
|
210
|
+
export function use${componentName}Query<T = ${responseTypes}>(${props}: ${componentName}QueryProps<T>) {
|
|
211
|
+
return useQuery(use${componentName}Query.queryKey(${key}), async () => ${fetchName}(${key}), { enabled: ${enabledParam}, ${options} });
|
|
209
212
|
}
|
|
210
213
|
|
|
211
214
|
use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
|
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
-
};
|
|
5
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.convertSwaggerFile = void 0;
|
|
7
|
-
const swagger2openapi_1 = __importDefault(require("swagger2openapi"));
|
|
8
|
-
const js_yaml_1 = __importDefault(require("js-yaml"));
|
|
9
|
-
/**
|
|
10
|
-
* Import and parse the openapi spec from a yaml/json
|
|
11
|
-
*/
|
|
12
|
-
const convertSwaggerFile = (data, extension) => {
|
|
13
|
-
const schema = extension === 'yaml' ? js_yaml_1.default.load(data) : JSON.parse(data);
|
|
14
|
-
return new Promise((resolve, reject) => {
|
|
15
|
-
if (!schema.openapi || !schema.openapi.startsWith('3.')) {
|
|
16
|
-
swagger2openapi_1.default.convertObj(schema, {}, (err, convertedObj) => {
|
|
17
|
-
if (err) {
|
|
18
|
-
reject(err);
|
|
19
|
-
}
|
|
20
|
-
else {
|
|
21
|
-
// @ts-ignore
|
|
22
|
-
convertedObj.openapi.basePath = convertedObj.original.basePath;
|
|
23
|
-
resolve(convertedObj.openapi);
|
|
24
|
-
}
|
|
25
|
-
});
|
|
26
|
-
}
|
|
27
|
-
else {
|
|
28
|
-
resolve(schema);
|
|
29
|
-
}
|
|
30
|
-
});
|
|
31
|
-
};
|
|
32
|
-
exports.convertSwaggerFile = convertSwaggerFile;
|
package/lib/cjs/generateHooks.js
DELETED
|
@@ -1,368 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
-
};
|
|
5
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.generateQueryHooks = exports.generateImports = void 0;
|
|
7
|
-
const lodash_1 = __importDefault(require("lodash"));
|
|
8
|
-
const { get, groupBy, uniq } = lodash_1.default;
|
|
9
|
-
const utils_js_1 = require("./utils.js");
|
|
10
|
-
const case_1 = __importDefault(require("case"));
|
|
11
|
-
const { pascal } = case_1.default;
|
|
12
|
-
const IdentifierRegexp = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
|
|
13
|
-
/**
|
|
14
|
-
* Return every params in a path
|
|
15
|
-
*/
|
|
16
|
-
const getParamsInPath = (path) => {
|
|
17
|
-
let n;
|
|
18
|
-
const output = [];
|
|
19
|
-
const templatePathRegex = /\{(\w+)}/g;
|
|
20
|
-
while ((n = templatePathRegex.exec(path)) !== null) {
|
|
21
|
-
output.push(n[1]);
|
|
22
|
-
}
|
|
23
|
-
return output;
|
|
24
|
-
};
|
|
25
|
-
const createQueryHooks = ({ componentName, responseTypes, enabledParam, emptyParams, }) => {
|
|
26
|
-
const params = emptyParams ? '' : `params: ${componentName}Params,`;
|
|
27
|
-
const key = emptyParams ? '' : `params`;
|
|
28
|
-
const mutationParams = emptyParams ? 'void' : `${componentName}Params`;
|
|
29
|
-
const queryParams = emptyParams ? '' : `${componentName}Params &`;
|
|
30
|
-
const filterParams = emptyParams
|
|
31
|
-
? '{ filters }: { filters?: QueryFilters }'
|
|
32
|
-
: `{ params, filters }: { params: ${componentName}Params, filters }`;
|
|
33
|
-
const cacheParams = emptyParams
|
|
34
|
-
? `{updater, options}: {updater: Updater<${responseTypes} | undefined, ${responseTypes} | undefined>, options?: SetDataOptions | undefined}`
|
|
35
|
-
: `{params, updater, options}: {params: ${componentName}Params, updater: Updater<${responseTypes} | undefined, ${responseTypes} | undefined>, options?: SetDataOptions | undefined}`;
|
|
36
|
-
const queryKey = emptyParams
|
|
37
|
-
? `use${componentName}Query.baseKey()`
|
|
38
|
-
: `[...use${componentName}Query.baseKey(), params]`;
|
|
39
|
-
const query = `
|
|
40
|
-
use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
|
|
41
|
-
|
|
42
|
-
use${componentName}Query.queryKey = (${params}): QueryKey => ${queryKey};
|
|
43
|
-
|
|
44
|
-
use${componentName}Query.updateCache = (${cacheParams}) => queryClient.setQueryData<${responseTypes}>(use${componentName}Query.queryKey(${key}), updater, options);
|
|
45
|
-
|
|
46
|
-
use${componentName}Query.getQueryState = (${filterParams})=> queryClient.getQueryState<${responseTypes}>(use${componentName}Query.queryKey(${key}), filters);
|
|
47
|
-
|
|
48
|
-
use${componentName}Query.getQueryData = (${filterParams})=> queryClient.getQueryData<${responseTypes}>(use${componentName}Query.queryKey(${key}), filters);
|
|
49
|
-
|
|
50
|
-
use${componentName}Query.prefetch = (${params}) => queryClient.prefetchQuery<${responseTypes}>(use${componentName}Query.queryKey(${key}), ()=> use${componentName}Query.fetch(${key}));
|
|
51
|
-
|
|
52
|
-
use${componentName}Query.cancelQueries = (${params}) => queryClient.cancelQueries(use${componentName}Query.queryKey(${key}))
|
|
53
|
-
|
|
54
|
-
use${componentName}Query.invalidate = (${params}) => queryClient.invalidateQueries<${responseTypes}>(use${componentName}Query.queryKey(${key}));
|
|
55
|
-
|
|
56
|
-
use${componentName}Query.refetchStale = (${params}) => queryClient.refetchQueries<${responseTypes}>(use${componentName}Query.queryKey(${key}), { stale: true });
|
|
57
|
-
|
|
58
|
-
type ${componentName}QueryProps<T = ${responseTypes}> = ${queryParams} {
|
|
59
|
-
options?: UseQueryOptions<${responseTypes}, AxiosError, T, any>
|
|
60
|
-
}
|
|
61
|
-
export function use${componentName}Query<T = ${responseTypes}>({ options = {}, ...params }: ${componentName}QueryProps<T>) {
|
|
62
|
-
return useQuery(use${componentName}Query.queryKey(${key}), async () => use${componentName}Query.fetch(${key}), { enabled: ${enabledParam}, ...options });
|
|
63
|
-
}`;
|
|
64
|
-
const mutation = `
|
|
65
|
-
type ${componentName}MutationProps<T> = {
|
|
66
|
-
options?: UseMutationOptions<${responseTypes}, AxiosError, ${mutationParams}, T>
|
|
67
|
-
}
|
|
68
|
-
export function use${componentName}Mutation<T = ${responseTypes}>(props?: ${componentName}MutationProps<T>) {
|
|
69
|
-
return useMutation(async (${key}) => use${componentName}Query.fetch(${key}), props?.options)
|
|
70
|
-
};`;
|
|
71
|
-
return query + mutation;
|
|
72
|
-
};
|
|
73
|
-
/**
|
|
74
|
-
* Generate a react-query component from openapi operation specs
|
|
75
|
-
*/
|
|
76
|
-
const createHook = ({ operation, verb, route, operationIds, parameters, schemasComponents, headerFilters, }) => {
|
|
77
|
-
const { operationId = route.replace('/', '') } = operation;
|
|
78
|
-
if (operationId === '*') {
|
|
79
|
-
throw new Error(`Invalid operationId/Route set for ${verb} ${route}`);
|
|
80
|
-
}
|
|
81
|
-
if (operationIds.includes(operationId)) {
|
|
82
|
-
throw new Error(`"${operationId}" is duplicated in your schema definition!`);
|
|
83
|
-
}
|
|
84
|
-
operationIds.push(operationId);
|
|
85
|
-
route = route.replace(/\{/g, '${').replace('//', '/'); // `/pet/{id}` => `/pet/${id}`
|
|
86
|
-
// Remove the last param of the route if we are in the DELETE case
|
|
87
|
-
let lastParamInTheRoute = null;
|
|
88
|
-
const componentName = pascal(operationId);
|
|
89
|
-
const isOk = ([statusCode]) => statusCode.toString().startsWith('2');
|
|
90
|
-
const responseTypes = (0, utils_js_1.getResReqTypes)(Object.entries(operation.responses).filter(isOk)) || 'void';
|
|
91
|
-
const requestBodyTypes = (0, utils_js_1.getResReqTypes)([['body', operation.requestBody]]);
|
|
92
|
-
let imports = [responseTypes];
|
|
93
|
-
const paramsInPath = getParamsInPath(route).filter((param) => !(verb === 'delete' && param === lastParamInTheRoute));
|
|
94
|
-
const { query: queryParams = [], path: pathParams = [], header = [], } = groupBy([...(parameters || []), ...(operation.parameters || [])].map((p) => {
|
|
95
|
-
if ((0, utils_js_1.isReference)(p)) {
|
|
96
|
-
return get(schemasComponents, p.$ref.replace('#/components/', '').replace('/', '.'));
|
|
97
|
-
}
|
|
98
|
-
else {
|
|
99
|
-
return p;
|
|
100
|
-
}
|
|
101
|
-
}), 'in');
|
|
102
|
-
const headerParams = header.filter((p) => !headerFilters?.includes(p.name));
|
|
103
|
-
let enabled = [];
|
|
104
|
-
// TODO: extract all requestBody or remove useQuery variants
|
|
105
|
-
let enabledParam = '!!params';
|
|
106
|
-
[...queryParams, ...pathParams, ...headerParams].forEach((item) => {
|
|
107
|
-
if (item.required) {
|
|
108
|
-
enabled.push(`["${item.name}"]`);
|
|
109
|
-
if (enabledParam && enabledParam !== '!!params') {
|
|
110
|
-
enabledParam += `&& params['${item.name}'] != null`;
|
|
111
|
-
}
|
|
112
|
-
else {
|
|
113
|
-
enabledParam = `params['${item.name}'] != null`;
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
});
|
|
117
|
-
// `!props${enabled.join('== null && !props')}`;
|
|
118
|
-
const paramsTypes = paramsInPath
|
|
119
|
-
.map((p) => {
|
|
120
|
-
try {
|
|
121
|
-
const { name, required, schema } = pathParams.find((i) => i.name === p);
|
|
122
|
-
return `${name}${required ? '' : '?'}: ${(0, utils_js_1.resolveValue)(schema)}`;
|
|
123
|
-
}
|
|
124
|
-
catch (err) {
|
|
125
|
-
throw new Error(`The path params ${p} can't be found in parameters (${operationId})`);
|
|
126
|
-
}
|
|
127
|
-
})
|
|
128
|
-
.join('; ');
|
|
129
|
-
const queryParamsType = queryParams
|
|
130
|
-
.map((p) => {
|
|
131
|
-
const processedName = IdentifierRegexp.test(p.name) ? p.name : `"${p.name}"`;
|
|
132
|
-
return `${(0, utils_js_1.formatDescription)(p.description)}${processedName}${p.required ? '' : '?'}: ${(0, utils_js_1.resolveValue)(p.schema)}`;
|
|
133
|
-
})
|
|
134
|
-
.join(';\n ');
|
|
135
|
-
const headerType = headerParams
|
|
136
|
-
.map((p) => {
|
|
137
|
-
try {
|
|
138
|
-
const { name, required, schema } = headerParams.find((i) => i.name === p.name);
|
|
139
|
-
return `"${name}"${required ? '' : '?'}: ${(0, utils_js_1.resolveValue)(schema)}`;
|
|
140
|
-
}
|
|
141
|
-
catch (err) {
|
|
142
|
-
throw new Error(`The path params ${p} can't be found in parameters (${operationId})`);
|
|
143
|
-
}
|
|
144
|
-
})
|
|
145
|
-
.join('; ');
|
|
146
|
-
// Retrieve the type of the param for delete verb
|
|
147
|
-
const lastParamInTheRouteDefinition = operation.parameters && lastParamInTheRoute
|
|
148
|
-
? operation.parameters.find((p) => {
|
|
149
|
-
if ((0, utils_js_1.isReference)(p)) {
|
|
150
|
-
return false;
|
|
151
|
-
}
|
|
152
|
-
return p.name === lastParamInTheRoute;
|
|
153
|
-
}) // Reference is not possible
|
|
154
|
-
: { schema: { type: 'string' } };
|
|
155
|
-
if (!lastParamInTheRouteDefinition) {
|
|
156
|
-
throw new Error(`The path params ${lastParamInTheRoute} can't be found in parameters (${operationId})`);
|
|
157
|
-
}
|
|
158
|
-
const description = (0, utils_js_1.formatDescription)(operation.summary && operation.description
|
|
159
|
-
? `${operation.summary}\n\n${operation.description}`
|
|
160
|
-
: `${operation.summary || ''}${operation.description || ''}`);
|
|
161
|
-
let output = `\n\n${description}`;
|
|
162
|
-
const headerParam = headerType && headerType !== 'void' ? `${headerType};` : '';
|
|
163
|
-
const queryParam = queryParamsType && queryParamsType !== 'void' ? `${queryParamsType}` : '';
|
|
164
|
-
const requestBodyComponent = requestBodyTypes && requestBodyTypes !== 'void' ? `${requestBodyTypes}` : '';
|
|
165
|
-
if (requestBodyComponent) {
|
|
166
|
-
imports.push(requestBodyComponent);
|
|
167
|
-
}
|
|
168
|
-
// QUERIES
|
|
169
|
-
if (!requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
|
|
170
|
-
output += `
|
|
171
|
-
// SECTION-A
|
|
172
|
-
use${componentName}Query.fetch = async () => {
|
|
173
|
-
const result = await api.${verb}<${responseTypes}>(\`${route}\`);
|
|
174
|
-
return result.data;
|
|
175
|
-
}
|
|
176
|
-
`;
|
|
177
|
-
output += createQueryHooks({ componentName, responseTypes, enabledParam, emptyParams: true });
|
|
178
|
-
}
|
|
179
|
-
if (!requestBodyComponent && paramsInPath.length && queryParam && !headerParam) {
|
|
180
|
-
output += `
|
|
181
|
-
// SECTION-B
|
|
182
|
-
type ${componentName}Params = {
|
|
183
|
-
${paramsTypes}
|
|
184
|
-
${queryParamsType};
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
use${componentName}Query.fetch = async (props:${componentName}Params) => {
|
|
188
|
-
const {${paramsInPath.join(', ')}, ...params} = props
|
|
189
|
-
const result = await api.${verb}<${responseTypes}>(\`${route}\`, {params})
|
|
190
|
-
return result.data;
|
|
191
|
-
}`;
|
|
192
|
-
output += createQueryHooks({ componentName, responseTypes, enabledParam });
|
|
193
|
-
}
|
|
194
|
-
if (!requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
|
|
195
|
-
output += `
|
|
196
|
-
// SECTION-C
|
|
197
|
-
type ${componentName}Params = {
|
|
198
|
-
${paramsTypes}
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
use${componentName}Query.fetch = async (props: ${componentName}Params ) => {
|
|
202
|
-
const result = await api.${verb}<${responseTypes}>(\`${route.replace(/\{/g, '{props.')}\`);
|
|
203
|
-
return result.data;
|
|
204
|
-
}
|
|
205
|
-
`;
|
|
206
|
-
output += createQueryHooks({ componentName, responseTypes, enabledParam });
|
|
207
|
-
}
|
|
208
|
-
if (!requestBodyComponent && !paramsInPath.length && queryParam && !headerParam) {
|
|
209
|
-
output += `
|
|
210
|
-
// SECTION-D
|
|
211
|
-
type ${componentName}Params = {
|
|
212
|
-
${queryParamsType}
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
use${componentName}Query.fetch = async (props: ${componentName}Params) => {
|
|
216
|
-
const result = await api.${verb}<${responseTypes}>(\`${route}\`, {params: props})
|
|
217
|
-
return result.data;
|
|
218
|
-
}
|
|
219
|
-
`;
|
|
220
|
-
output += createQueryHooks({ componentName, responseTypes, enabledParam });
|
|
221
|
-
}
|
|
222
|
-
if (requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
|
|
223
|
-
output += `
|
|
224
|
-
// SECTION-E
|
|
225
|
-
type ${componentName}Params = ${requestBodyComponent}
|
|
226
|
-
|
|
227
|
-
use${componentName}Query.fetch = async (body: ${componentName}Params) => {
|
|
228
|
-
const result = await api.${verb}<${responseTypes}>(\`${route}\`, body)
|
|
229
|
-
return result.data
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
`;
|
|
233
|
-
output += createQueryHooks({ componentName, responseTypes, enabledParam });
|
|
234
|
-
}
|
|
235
|
-
if (requestBodyComponent && !paramsInPath.length && queryParam && !headerParam) {
|
|
236
|
-
output += `
|
|
237
|
-
// SECTION-G
|
|
238
|
-
// TODO: LOOKS BROKEN
|
|
239
|
-
type ${componentName}Params = {
|
|
240
|
-
body: ${requestBodyComponent}
|
|
241
|
-
queryParams: ${queryParamsType}
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
type ${componentName}QueryProps<T = ${responseTypes}> = ${componentName}Params & {
|
|
245
|
-
options?: UseQueryOptions<${responseTypes}, AxiosError, T, any>
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
use${componentName}Query.fetch = async ({body, queryParams}: ${componentName}Params) => {
|
|
249
|
-
const result = await api.${verb}<${responseTypes}>(\`${route}\`, body, {params: queryParams})
|
|
250
|
-
return result.data
|
|
251
|
-
}
|
|
252
|
-
`;
|
|
253
|
-
output += createQueryHooks({ componentName, responseTypes, enabledParam });
|
|
254
|
-
}
|
|
255
|
-
if (!requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
|
|
256
|
-
output += `
|
|
257
|
-
// SECTION-H
|
|
258
|
-
type ${componentName}Params = {
|
|
259
|
-
${headerParam}
|
|
260
|
-
};
|
|
261
|
-
|
|
262
|
-
use${componentName}Query.fetch = async (headers: ${componentName}Params) => {
|
|
263
|
-
const result = await api.${verb}<${responseTypes}>(\`${route}\`, {headers});
|
|
264
|
-
return result.data;
|
|
265
|
-
}
|
|
266
|
-
`;
|
|
267
|
-
output += createQueryHooks({ componentName, responseTypes, enabledParam });
|
|
268
|
-
}
|
|
269
|
-
if (requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
|
|
270
|
-
output += `
|
|
271
|
-
// SECTION-J
|
|
272
|
-
type ${componentName}Params = {
|
|
273
|
-
body: ${requestBodyComponent}
|
|
274
|
-
headers: {${headerParam}}
|
|
275
|
-
};
|
|
276
|
-
|
|
277
|
-
use${componentName}Query.fetch = async ({headers, body}: ${componentName}Params) => {
|
|
278
|
-
const result = await api.${verb}<${responseTypes}>(\`${route}\`, body, {headers})
|
|
279
|
-
return result.data
|
|
280
|
-
}`;
|
|
281
|
-
output += createQueryHooks({ componentName, responseTypes, enabledParam });
|
|
282
|
-
}
|
|
283
|
-
if (!requestBodyComponent && !paramsInPath.length && queryParam && headerParam) {
|
|
284
|
-
output += `
|
|
285
|
-
// SECTION-K
|
|
286
|
-
type ${componentName}Params = {
|
|
287
|
-
headers: {${headerParam}}
|
|
288
|
-
queryParams: {${queryParamsType} }
|
|
289
|
-
}
|
|
290
|
-
use${componentName}Query.fetch = async ({headers, queryParams}: ${componentName}Params) => {
|
|
291
|
-
const result = await api.${verb}<${responseTypes}>(\`${route}\`, body, {headers, params: queryParams})
|
|
292
|
-
return result.data
|
|
293
|
-
}`;
|
|
294
|
-
output += createQueryHooks({ componentName, responseTypes, enabledParam });
|
|
295
|
-
}
|
|
296
|
-
if (requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
|
|
297
|
-
output += `// TODO: NOT SUPPORTED requestBodyComponent && paramsInPath)`;
|
|
298
|
-
}
|
|
299
|
-
if (requestBodyComponent && paramsInPath.length && queryParam && !headerParam) {
|
|
300
|
-
output += `// TODO: NOT SUPPORTED requestBodyComponent && paramsInPath && queryParam)`;
|
|
301
|
-
}
|
|
302
|
-
if (requestBodyComponent && !paramsInPath.length && queryParam && headerParam) {
|
|
303
|
-
output += `// TODO: NOT SUPPORTED requestBodyComponent && queryParam && headerParam)`;
|
|
304
|
-
}
|
|
305
|
-
if (requestBodyComponent && paramsInPath.length && queryParam && headerParam) {
|
|
306
|
-
output += `// TODO: NOT SUPPORTED requestBodyComponent && paramsInPath && queryParam && headerParam)`;
|
|
307
|
-
}
|
|
308
|
-
if (!requestBodyComponent && paramsInPath.length && !queryParam && headerParam) {
|
|
309
|
-
output += `// TODO: NOT SUPPORTED (paramsInPath && headerParam)`;
|
|
310
|
-
}
|
|
311
|
-
if (!requestBodyComponent && paramsInPath.length && queryParam && headerParam) {
|
|
312
|
-
output += `// TODO: NOT SUPPORTED (paramsInPath && queryParam && headerParam)`;
|
|
313
|
-
}
|
|
314
|
-
if (requestBodyComponent && paramsInPath.length && !queryParam && headerParam) {
|
|
315
|
-
output += `// TODO: NOT SUPPORTED (requestBodyComponent && paramsInPath && headerParam)`;
|
|
316
|
-
}
|
|
317
|
-
return { implementation: output, imports };
|
|
318
|
-
};
|
|
319
|
-
const generateImports = ({ schemaName, apiDirectory, queryClientDir, schemaImports, }) => {
|
|
320
|
-
const importTypes = schemaImports.join(',');
|
|
321
|
-
return `
|
|
322
|
-
import {
|
|
323
|
-
useQuery,
|
|
324
|
-
useMutation,
|
|
325
|
-
UseQueryOptions,
|
|
326
|
-
UseMutationOptions,
|
|
327
|
-
QueryKey,
|
|
328
|
-
SetDataOptions,
|
|
329
|
-
QueryFilters
|
|
330
|
-
} from '@tanstack/react-query';
|
|
331
|
-
|
|
332
|
-
import { AxiosError } from 'axios';
|
|
333
|
-
import { api } from '${apiDirectory}';
|
|
334
|
-
import { queryClient } from '${queryClientDir}';
|
|
335
|
-
|
|
336
|
-
import {${importTypes}} from './${schemaName}'
|
|
337
|
-
|
|
338
|
-
type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput);
|
|
339
|
-
`;
|
|
340
|
-
};
|
|
341
|
-
exports.generateImports = generateImports;
|
|
342
|
-
const generateQueryHooks = ({ spec, operationIds, headerFilters, }) => {
|
|
343
|
-
const { paths, components } = spec;
|
|
344
|
-
let hooks = '';
|
|
345
|
-
let schemaImports = [];
|
|
346
|
-
Object.entries(paths).forEach(([route, verbs]) => {
|
|
347
|
-
Object.entries(verbs).forEach(([verb, operation]) => {
|
|
348
|
-
if (['get', 'post', 'patch', 'put', 'delete'].includes(verb) && !operation.deprecated) {
|
|
349
|
-
const { implementation, imports } = createHook({
|
|
350
|
-
operation,
|
|
351
|
-
verb,
|
|
352
|
-
route: spec.basePath + route,
|
|
353
|
-
operationIds,
|
|
354
|
-
parameters: verbs.parameters,
|
|
355
|
-
schemasComponents: components,
|
|
356
|
-
headerFilters,
|
|
357
|
-
});
|
|
358
|
-
hooks += implementation;
|
|
359
|
-
imports.forEach((element) => {
|
|
360
|
-
schemaImports.push(element.replace('[]', ''));
|
|
361
|
-
});
|
|
362
|
-
}
|
|
363
|
-
});
|
|
364
|
-
});
|
|
365
|
-
const schemaImportsFiltered = schemaImports.filter((item) => !!item && item !== 'void' && item !== 'boolean' && item !== 'undefined' && item !== 'string');
|
|
366
|
-
return { implementation: hooks, schemaImports: uniq(schemaImportsFiltered) };
|
|
367
|
-
};
|
|
368
|
-
exports.generateQueryHooks = generateQueryHooks;
|