react-query-lightbase-codegen 0.5.0 → 1.0.2
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/README.md +76 -0
- package/package.json +36 -4
- package/lib/cjs/convertSwaggerFile.js +0 -32
- package/lib/cjs/generateHooks.js +0 -401
- package/lib/cjs/generateImports.js +0 -31
- package/lib/cjs/generateRequestBodiesDefinition.js +0 -36
- package/lib/cjs/generateResponsesDefinition.js +0 -36
- package/lib/cjs/generateSchemas.js +0 -103
- package/lib/cjs/generateSchemasDefinition.js +0 -40
- package/lib/cjs/getResReqTypes.js +0 -162
- package/lib/cjs/import-open-api.js +0 -39
- package/lib/cjs/importSpecs.js +0 -87
- package/lib/cjs/index.js +0 -7
- package/lib/cjs/react-query-codegen-import.js +0 -49
- package/lib/cjs/resolveDiscriminator.js +0 -31
- package/lib/cjs/types.js +0 -2
- package/lib/cjs/utils.js +0 -168
- package/lib/esm/convertSwaggerFile.js +0 -25
- package/lib/esm/generateHooks.js +0 -394
- package/lib/esm/generateImports.js +0 -27
- package/lib/esm/generateRequestBodiesDefinition.js +0 -29
- package/lib/esm/generateResponsesDefinition.js +0 -29
- package/lib/esm/generateSchemas.js +0 -96
- package/lib/esm/generateSchemasDefinition.js +0 -33
- package/lib/esm/getResReqTypes.js +0 -150
- package/lib/esm/import-open-api.js +0 -32
- package/lib/esm/importSpecs.js +0 -80
- package/lib/esm/index.js +0 -3
- package/lib/esm/react-query-codegen-import.js +0 -42
- package/lib/esm/resolveDiscriminator.js +0 -24
- package/lib/esm/types.js +0 -1
- package/lib/esm/utils.js +0 -156
package/README.md
CHANGED
|
@@ -1 +1,77 @@
|
|
|
1
|
+
# React Query Code Generation
|
|
1
2
|
|
|
3
|
+
Generate fully typed react query hooks from OpenAPI specifications.
|
|
4
|
+
|
|
5
|
+
- GET requests will automatically generate `useQuery` hooks together with helper functions
|
|
6
|
+
- getQueryState
|
|
7
|
+
- getQueryData
|
|
8
|
+
- prefetch
|
|
9
|
+
- cancelQueries
|
|
10
|
+
- invalidate
|
|
11
|
+
- refetchStale
|
|
12
|
+
|
|
13
|
+
- Override default generation forcing query, mutation or infiniteQuery output
|
|
14
|
+
|
|
15
|
+
## Installation
|
|
16
|
+
|
|
17
|
+
You can install react-query-lightbase-codegen with NPM or Yarn.
|
|
18
|
+
|
|
19
|
+
Using NPM:
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
$ npm i -D react-query-lightbase-codegen
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Using Yarn:
|
|
26
|
+
|
|
27
|
+
```
|
|
28
|
+
$ yarn add -D react-query-lightbase-codegen
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Configuration
|
|
32
|
+
|
|
33
|
+
create a generateQueries.mjs file in project root folder
|
|
34
|
+
|
|
35
|
+
```javascript
|
|
36
|
+
// generateQueries.mjs
|
|
37
|
+
import { importSpecs } from 'react-query-lightbase-codegen';
|
|
38
|
+
|
|
39
|
+
importSpecs({
|
|
40
|
+
// folder location of the openapi/swagger documents (yaml or JSON)
|
|
41
|
+
sourceDirectory: './specs',
|
|
42
|
+
// export folder for hooks and schema code generated files
|
|
43
|
+
exportDirectory: './src/generated',
|
|
44
|
+
// api client - as named export labelled 'api'
|
|
45
|
+
apiDirectory: './src/api',
|
|
46
|
+
// React query client directory - names export 'queryClient'
|
|
47
|
+
queryClientDir: './src/api',
|
|
48
|
+
});
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Code generation
|
|
52
|
+
|
|
53
|
+
To generate the code generated scheme and react query hooks run the above script
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
node scripts/generateQueries.mjs && prettier --check ./src/generated/*.tsx --write
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Configuration Options
|
|
60
|
+
|
|
61
|
+
```javascript
|
|
62
|
+
// generateQueries.mjs
|
|
63
|
+
import { importSpecs } from 'react-query-lightbase-codegen';
|
|
64
|
+
|
|
65
|
+
importSpecs({
|
|
66
|
+
...
|
|
67
|
+
// Filter out any headers from individual queries (these might be applied globally in the axios instance)
|
|
68
|
+
headerFilters: ['X-Session-Token'],
|
|
69
|
+
overrides: {
|
|
70
|
+
// operationId listed in the openApi spec
|
|
71
|
+
findPetsByStatus: {
|
|
72
|
+
// Override the default query code generation type ('query' | 'mutation' | 'infiniteQuery')
|
|
73
|
+
type: 'query',
|
|
74
|
+
},
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
```
|
package/package.json
CHANGED
|
@@ -1,19 +1,43 @@
|
|
|
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.0.2",
|
|
4
5
|
"license": "MIT",
|
|
5
6
|
"type": "module",
|
|
6
|
-
"exports": "./
|
|
7
|
+
"exports": "./dist/index.js",
|
|
7
8
|
"files": [
|
|
8
9
|
"lib/"
|
|
9
10
|
],
|
|
11
|
+
"keywords": [
|
|
12
|
+
"rest",
|
|
13
|
+
"client",
|
|
14
|
+
"swagger",
|
|
15
|
+
"open-api",
|
|
16
|
+
"fetch",
|
|
17
|
+
"data fetching",
|
|
18
|
+
"code-generation",
|
|
19
|
+
"react",
|
|
20
|
+
"react-query",
|
|
21
|
+
"axios",
|
|
22
|
+
"vue-query",
|
|
23
|
+
"tanstack"
|
|
24
|
+
],
|
|
25
|
+
"author": {
|
|
26
|
+
"name": "Oliver Winter",
|
|
27
|
+
"email": "owinter86@gmail.com"
|
|
28
|
+
},
|
|
29
|
+
"repository": {
|
|
30
|
+
"type": "git",
|
|
31
|
+
"url": "https://github.com/owinter86/react-query-codegen"
|
|
32
|
+
},
|
|
10
33
|
"engines": {
|
|
11
34
|
"node": ">=14.16"
|
|
12
35
|
},
|
|
13
36
|
"scripts": {
|
|
14
37
|
"lint": "eslint . --ext .js,.jsx,.ts,.tsx",
|
|
15
|
-
"tsc": "tsc -p tsconfig.json
|
|
16
|
-
"test": "yarn tsc && node test/script.mjs && prettier --check ./test/generated/**/*.tsx --write && eslint ./test/generated/**/*.tsx --fix"
|
|
38
|
+
"tsc": "tsc -p tsconfig.json",
|
|
39
|
+
"test": "yarn tsc && node test/script.mjs && prettier --check ./test/generated/**/*.tsx --write && eslint ./test/generated/**/*.tsx --fix",
|
|
40
|
+
"prepare": "husky install"
|
|
17
41
|
},
|
|
18
42
|
"dependencies": {
|
|
19
43
|
"axios": "0.27.2",
|
|
@@ -28,7 +52,13 @@
|
|
|
28
52
|
"devDependencies": {
|
|
29
53
|
"@babel/core": "7.18.10",
|
|
30
54
|
"@babel/eslint-parser": "7.17.0",
|
|
55
|
+
"@commitlint/cli": "^17.0.3",
|
|
56
|
+
"@commitlint/config-conventional": "^17.0.3",
|
|
31
57
|
"@react-native-community/eslint-config": "3.1.0",
|
|
58
|
+
"@semantic-release/changelog": "^6.0.1",
|
|
59
|
+
"@semantic-release/git": "^10.0.1",
|
|
60
|
+
"@semantic-release/github": "^8.0.5",
|
|
61
|
+
"@semantic-release/npm": "^9.0.1",
|
|
32
62
|
"@tanstack/react-query": "4.0.10",
|
|
33
63
|
"@types/js-yaml": "4.0.5",
|
|
34
64
|
"@types/lodash": "4.14.182",
|
|
@@ -38,8 +68,10 @@
|
|
|
38
68
|
"@types/yamljs": "0.2.31",
|
|
39
69
|
"eslint": "8.21.0",
|
|
40
70
|
"eslint-plugin-prettier": "4.2.1",
|
|
71
|
+
"husky": "^8.0.1",
|
|
41
72
|
"prettier": "2.7.1",
|
|
42
73
|
"react": "17.0.2",
|
|
74
|
+
"semantic-release": "^19.0.3",
|
|
43
75
|
"typescript": "4.7.4"
|
|
44
76
|
}
|
|
45
77
|
}
|
|
@@ -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,401 +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.createHook = void 0;
|
|
7
|
-
const lodash_1 = __importDefault(require("lodash"));
|
|
8
|
-
const { get, groupBy } = lodash_1.default;
|
|
9
|
-
const utils_js_1 = require("./utils.js");
|
|
10
|
-
const case_1 = __importDefault(require("case"));
|
|
11
|
-
const chalk_1 = __importDefault(require("chalk"));
|
|
12
|
-
const { pascal, camel } = case_1.default;
|
|
13
|
-
const IdentifierRegexp = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
|
|
14
|
-
/**
|
|
15
|
-
* Return every params in a path
|
|
16
|
-
*/
|
|
17
|
-
const getParamsInPath = (path) => {
|
|
18
|
-
let n;
|
|
19
|
-
const output = [];
|
|
20
|
-
const templatePathRegex = /\{(\w+)}/g;
|
|
21
|
-
while ((n = templatePathRegex.exec(path)) !== null) {
|
|
22
|
-
output.push(n[1]);
|
|
23
|
-
}
|
|
24
|
-
return output;
|
|
25
|
-
};
|
|
26
|
-
/**
|
|
27
|
-
* Generate a react-query component from openapi operation specs
|
|
28
|
-
*/
|
|
29
|
-
const createHook = ({ operation, verb, route, operationIds, parameters, schemasComponents, headerFilters, overrides, }) => {
|
|
30
|
-
const { operationId = route.replace('/', '') } = operation;
|
|
31
|
-
if (operationId === '*') {
|
|
32
|
-
throw new Error(`Invalid operationId/Route set for ${verb} ${route}`);
|
|
33
|
-
}
|
|
34
|
-
if (operationIds.includes(operationId)) {
|
|
35
|
-
return { implementation: '', imports: [], queryImports: [] };
|
|
36
|
-
}
|
|
37
|
-
operationIds.push(operationId);
|
|
38
|
-
route = route.replace(/\{/g, '${').replace('//', '/'); // `/pet/{id}` => `/pet/${id}`
|
|
39
|
-
// Remove the last param of the route if we are in the DELETE case
|
|
40
|
-
let lastParamInTheRoute = null;
|
|
41
|
-
const componentName = pascal(operationId);
|
|
42
|
-
const isOk = ([statusCode]) => statusCode.toString().startsWith('2');
|
|
43
|
-
const responseTypes = (0, utils_js_1.getResReqTypes)(Object.entries(operation.responses).filter(isOk)) || 'void';
|
|
44
|
-
const requestBodyTypes = (0, utils_js_1.getResReqTypes)([['body', operation.requestBody]]);
|
|
45
|
-
let imports = [responseTypes];
|
|
46
|
-
let queryImports = [];
|
|
47
|
-
const paramsInPath = getParamsInPath(route).filter((param) => !(verb === 'delete' && param === lastParamInTheRoute));
|
|
48
|
-
const { query: queryParams = [], path: pathParams = [], header = [], } = groupBy([...(parameters || []), ...(operation.parameters || [])].map((p) => {
|
|
49
|
-
if ((0, utils_js_1.isReference)(p)) {
|
|
50
|
-
return get(schemasComponents, p.$ref.replace('#/components/', '').replace('/', '.'));
|
|
51
|
-
}
|
|
52
|
-
else {
|
|
53
|
-
return p;
|
|
54
|
-
}
|
|
55
|
-
}), 'in');
|
|
56
|
-
const headerParams = header.filter((p) => !headerFilters?.includes(p.name));
|
|
57
|
-
let enabled = [];
|
|
58
|
-
// TODO: extract all requestBody or remove useQuery variants
|
|
59
|
-
let enabledParam = '!!params';
|
|
60
|
-
[...queryParams, ...pathParams, ...headerParams].forEach((item) => {
|
|
61
|
-
if (item.required) {
|
|
62
|
-
enabled.push(`["${item.name}"]`);
|
|
63
|
-
if (enabledParam && enabledParam !== '!!params') {
|
|
64
|
-
enabledParam += `&& params['${item.name}'] != null`;
|
|
65
|
-
}
|
|
66
|
-
else {
|
|
67
|
-
enabledParam = `params['${item.name}'] != null`;
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
});
|
|
71
|
-
// `!props${enabled.join('== null && !props')}`;
|
|
72
|
-
const paramsTypes = paramsInPath
|
|
73
|
-
.map((p) => {
|
|
74
|
-
try {
|
|
75
|
-
const { name, required, schema } = pathParams.find((i) => i.name === p);
|
|
76
|
-
return `${name}${required ? '' : '?'}: ${(0, utils_js_1.resolveValue)(schema)}`;
|
|
77
|
-
}
|
|
78
|
-
catch (err) {
|
|
79
|
-
throw new Error(`The path params ${p} can't be found in parameters (${operationId})`);
|
|
80
|
-
}
|
|
81
|
-
})
|
|
82
|
-
.join('; ');
|
|
83
|
-
const queryParamsType = queryParams
|
|
84
|
-
.map((p) => {
|
|
85
|
-
const processedName = IdentifierRegexp.test(p.name) ? p.name : `"${p.name}"`;
|
|
86
|
-
return `${(0, utils_js_1.formatDescription)(p.description)}
|
|
87
|
-
${processedName}${p.required ? '' : '?'}: ${(0, utils_js_1.resolveValue)(p.schema)}`;
|
|
88
|
-
})
|
|
89
|
-
.join(';\n ');
|
|
90
|
-
const headerType = headerParams
|
|
91
|
-
.map((p) => {
|
|
92
|
-
try {
|
|
93
|
-
const { name, required, schema } = headerParams.find((i) => i.name === p.name);
|
|
94
|
-
return `"${name}"${required ? '' : '?'}: ${(0, utils_js_1.resolveValue)(schema)}`;
|
|
95
|
-
}
|
|
96
|
-
catch (err) {
|
|
97
|
-
throw new Error(`The path params ${p} can't be found in parameters (${operationId})`);
|
|
98
|
-
}
|
|
99
|
-
})
|
|
100
|
-
.join('; ');
|
|
101
|
-
// Retrieve the type of the param for delete verb
|
|
102
|
-
const lastParamInTheRouteDefinition = operation.parameters && lastParamInTheRoute
|
|
103
|
-
? operation.parameters.find((p) => {
|
|
104
|
-
if ((0, utils_js_1.isReference)(p)) {
|
|
105
|
-
return false;
|
|
106
|
-
}
|
|
107
|
-
return p.name === lastParamInTheRoute;
|
|
108
|
-
}) // Reference is not possible
|
|
109
|
-
: { schema: { type: 'string' } };
|
|
110
|
-
if (!lastParamInTheRouteDefinition) {
|
|
111
|
-
throw new Error(`The path params ${lastParamInTheRoute} can't be found in parameters (${operationId})`);
|
|
112
|
-
}
|
|
113
|
-
const defaultDescription = `type: ${verb}\noperationId: ${operationId}\nurl: ${route}`;
|
|
114
|
-
const description = (0, utils_js_1.formatDescription)(operation.summary && operation.description
|
|
115
|
-
? `${defaultDescription}\n\n${operation.summary}\n\n${operation.description}`
|
|
116
|
-
: `${defaultDescription}`);
|
|
117
|
-
let output = `\n\n${description}`;
|
|
118
|
-
const headerParam = headerType && headerType !== 'void' ? `${headerType};` : '';
|
|
119
|
-
const queryParam = queryParamsType && queryParamsType !== 'void' ? `${queryParamsType}` : '';
|
|
120
|
-
const requestBodyComponent = requestBodyTypes && requestBodyTypes !== 'void' ? `${requestBodyTypes}` : '';
|
|
121
|
-
if (requestBodyComponent) {
|
|
122
|
-
imports.push(requestBodyComponent);
|
|
123
|
-
}
|
|
124
|
-
const isUpdateRequest = ['post', 'patch', 'put'].includes(verb);
|
|
125
|
-
const generateProps = (props) => {
|
|
126
|
-
return props.map((item) => `["${item.name}"]: props["${item.name}"]`).join(',');
|
|
127
|
-
};
|
|
128
|
-
const generateBodyProps = () => {
|
|
129
|
-
const definitionKey = Object.keys(schemasComponents?.schemas || {}).find((key) => pascal(key) === requestBodyComponent);
|
|
130
|
-
if (definitionKey) {
|
|
131
|
-
const scheme = schemasComponents?.schemas?.[definitionKey];
|
|
132
|
-
return Object.keys(scheme.properties)
|
|
133
|
-
.map((item) => `["${item}"]: props["${item}"]`)
|
|
134
|
-
.join(',');
|
|
135
|
-
}
|
|
136
|
-
};
|
|
137
|
-
const fetchName = camel(componentName);
|
|
138
|
-
const createQueryHooks = (emptyParams) => {
|
|
139
|
-
const params = emptyParams ? '' : `params: ${componentName}Params,`;
|
|
140
|
-
const key = emptyParams ? '' : `params`;
|
|
141
|
-
const mutationParams = emptyParams ? 'void' : `${componentName}Params`;
|
|
142
|
-
const queryParamType = emptyParams ? '' : `${componentName}Params &`;
|
|
143
|
-
const filterParams = emptyParams
|
|
144
|
-
? '{ filters }: { filters?: QueryFilters }'
|
|
145
|
-
: `{ params, filters }: { params: ${componentName}Params, filters?: QueryFilters }`;
|
|
146
|
-
const cacheParams = emptyParams
|
|
147
|
-
? `{updater, options}: {updater: Updater<${responseTypes} | undefined, ${responseTypes} | undefined>, options?: SetDataOptions | undefined}`
|
|
148
|
-
: `{params, updater, options}: {params: ${componentName}Params, updater: Updater<${responseTypes} | undefined, ${responseTypes} | undefined>, options?: SetDataOptions | undefined}`;
|
|
149
|
-
const queryKey = emptyParams
|
|
150
|
-
? `use${componentName}Query.baseKey()`
|
|
151
|
-
: `[...use${componentName}Query.baseKey(), params]`;
|
|
152
|
-
const createQuery = () => `
|
|
153
|
-
type ${componentName}QueryProps<T = ${responseTypes}> = ${queryParamType} {
|
|
154
|
-
options?: UseQueryOptions<${responseTypes}, AxiosError, T, any>
|
|
155
|
-
}
|
|
156
|
-
export function use${componentName}Query<T = ${responseTypes}>({ options = {}, ...params }: ${componentName}QueryProps<T>) {
|
|
157
|
-
return useQuery(use${componentName}Query.queryKey(${key}), async () => ${fetchName}(${key}), { enabled: ${enabledParam}, ...options });
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
|
|
161
|
-
|
|
162
|
-
use${componentName}Query.queryKey = (${params}): QueryKey => ${queryKey};
|
|
163
|
-
|
|
164
|
-
use${componentName}Query.updateCache = (${cacheParams}) => queryClient.setQueryData<${responseTypes}>(use${componentName}Query.queryKey(${key}), updater, options);
|
|
165
|
-
|
|
166
|
-
use${componentName}Query.getQueryState = (${filterParams})=> queryClient.getQueryState<${responseTypes}>(use${componentName}Query.queryKey(${key}), filters);
|
|
167
|
-
|
|
168
|
-
use${componentName}Query.getQueryData = (${filterParams})=> queryClient.getQueryData<${responseTypes}>(use${componentName}Query.queryKey(${key}), filters);
|
|
169
|
-
|
|
170
|
-
use${componentName}Query.prefetch = (${params}) => queryClient.prefetchQuery<${responseTypes}>(use${componentName}Query.queryKey(${key}), ()=> ${fetchName}(${key}));
|
|
171
|
-
|
|
172
|
-
use${componentName}Query.cancelQueries = (${params}) => queryClient.cancelQueries(use${componentName}Query.queryKey(${key}))
|
|
173
|
-
|
|
174
|
-
use${componentName}Query.invalidate = (${params}) => queryClient.invalidateQueries<${responseTypes}>(use${componentName}Query.queryKey(${key}));
|
|
175
|
-
|
|
176
|
-
use${componentName}Query.refetchStale = (${params}) => queryClient.refetchQueries<${responseTypes}>(use${componentName}Query.queryKey(${key}), { stale: true });
|
|
177
|
-
`;
|
|
178
|
-
const getInfiniteQuery = ({ pageParam }) => `
|
|
179
|
-
type ${componentName}QueryProps<T = ${responseTypes}> = ${queryParamType} {
|
|
180
|
-
options: UseInfiniteQueryOptions<${responseTypes}, AxiosError, T, any>
|
|
181
|
-
}
|
|
182
|
-
export function use${componentName}Query<T = ${responseTypes}>({ options = {}, ...params }: ${componentName}QueryProps<T>) {
|
|
183
|
-
return useInfiniteQuery(use${componentName}Query.queryKey(${key}), async ({ pageParam = 0 }) => ${fetchName}({${pageParam}: pageParam, ...params}), { enabled: ${enabledParam}, ...options });
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
|
|
187
|
-
|
|
188
|
-
use${componentName}Query.queryKey = (${params}): QueryKey => ${queryKey};
|
|
189
|
-
|
|
190
|
-
`;
|
|
191
|
-
const createMutation = () => `
|
|
192
|
-
type ${componentName}MutationProps<T> = {
|
|
193
|
-
options?: UseMutationOptions<${responseTypes}, AxiosError, ${mutationParams}, T>
|
|
194
|
-
}
|
|
195
|
-
export function use${componentName}Mutation<T = ${responseTypes}>(props?: ${componentName}MutationProps<T>) {
|
|
196
|
-
return useMutation(async (${key}) => ${fetchName}(${key}), props?.options)
|
|
197
|
-
};
|
|
198
|
-
`;
|
|
199
|
-
const override = overrides?.[operationId];
|
|
200
|
-
if (override?.type === 'query') {
|
|
201
|
-
console.log(chalk_1.default.blue(`⚙️ [${operationId}] has been changed to a useQuery hook`));
|
|
202
|
-
queryImports.push('query');
|
|
203
|
-
return createQuery();
|
|
204
|
-
}
|
|
205
|
-
if (override?.type === 'mutation') {
|
|
206
|
-
queryImports.push('mutation');
|
|
207
|
-
console.log(chalk_1.default.blue(`⚙️ [${operationId}] has been changed to a useMutation hook`));
|
|
208
|
-
return createMutation();
|
|
209
|
-
}
|
|
210
|
-
if (override?.type === 'infiniteQuery') {
|
|
211
|
-
console.log(chalk_1.default.blue(`⚙️ [${operationId}] has been changed to a useInfiniteQuery hook`));
|
|
212
|
-
queryImports.push('infiniteQuery');
|
|
213
|
-
return getInfiniteQuery({ pageParam: override.infiniteQueryParm });
|
|
214
|
-
}
|
|
215
|
-
if (verb === 'get') {
|
|
216
|
-
queryImports.push('query');
|
|
217
|
-
return createQuery();
|
|
218
|
-
}
|
|
219
|
-
queryImports.push('mutation');
|
|
220
|
-
return createMutation();
|
|
221
|
-
};
|
|
222
|
-
output += createQueryHooks(!requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam);
|
|
223
|
-
if (!requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
|
|
224
|
-
output += `
|
|
225
|
-
const ${fetchName} = async () => {
|
|
226
|
-
const result = await api.${verb}<${responseTypes}>(\`${route}\`);
|
|
227
|
-
return result.data;
|
|
228
|
-
}
|
|
229
|
-
`;
|
|
230
|
-
}
|
|
231
|
-
if (!requestBodyComponent && paramsInPath.length && queryParam && !headerParam) {
|
|
232
|
-
const config = isUpdateRequest ? 'body,{params}' : '{params}';
|
|
233
|
-
output += `
|
|
234
|
-
type ${componentName}Params = {
|
|
235
|
-
${paramsTypes}
|
|
236
|
-
${queryParamsType};
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
const ${fetchName} = async (props:${componentName}Params) => {
|
|
240
|
-
const {${paramsInPath.join(', ')}, ...params} = props
|
|
241
|
-
const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config})
|
|
242
|
-
return result.data;
|
|
243
|
-
}`;
|
|
244
|
-
}
|
|
245
|
-
if (!requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
|
|
246
|
-
output += `
|
|
247
|
-
type ${componentName}Params = {
|
|
248
|
-
${paramsTypes}
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
const ${fetchName} = async (props: ${componentName}Params ) => {
|
|
252
|
-
const result = await api.${verb}<${responseTypes}>(\`${route.replace(/\{/g, '{props.')}\`);
|
|
253
|
-
return result.data;
|
|
254
|
-
}
|
|
255
|
-
`;
|
|
256
|
-
}
|
|
257
|
-
if (!requestBodyComponent && !paramsInPath.length && queryParam && !headerParam) {
|
|
258
|
-
const config = isUpdateRequest ? 'null,{params}' : '{params}';
|
|
259
|
-
output += `
|
|
260
|
-
type ${componentName}Params = {
|
|
261
|
-
${queryParamsType}
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
const ${fetchName} = async (params: ${componentName}Params) => {
|
|
265
|
-
const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config})
|
|
266
|
-
return result.data;
|
|
267
|
-
}
|
|
268
|
-
`;
|
|
269
|
-
}
|
|
270
|
-
if (!requestBodyComponent && !paramsInPath.length && queryParam && headerParam) {
|
|
271
|
-
const config = isUpdateRequest ? 'null,{headers, params: queryParams}' : '{headers, params: queryParams}';
|
|
272
|
-
output += `
|
|
273
|
-
type ${componentName}Params = {
|
|
274
|
-
${headerParam}
|
|
275
|
-
${queryParamsType}
|
|
276
|
-
}
|
|
277
|
-
const ${fetchName} = async (props: ${componentName}Params) => {
|
|
278
|
-
const headers = {${generateProps(header)}}
|
|
279
|
-
const queryParams = {${generateProps(queryParams)}}
|
|
280
|
-
const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config})
|
|
281
|
-
return result.data
|
|
282
|
-
}`;
|
|
283
|
-
}
|
|
284
|
-
if (!requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
|
|
285
|
-
const config = isUpdateRequest ? 'null,{headers}' : '{headers}';
|
|
286
|
-
output += `
|
|
287
|
-
type ${componentName}Params = {
|
|
288
|
-
${headerParam}
|
|
289
|
-
};
|
|
290
|
-
|
|
291
|
-
const ${fetchName} = async (headers: ${componentName}Params) => {
|
|
292
|
-
const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config});
|
|
293
|
-
return result.data;
|
|
294
|
-
}
|
|
295
|
-
`;
|
|
296
|
-
}
|
|
297
|
-
if (requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
|
|
298
|
-
output += `
|
|
299
|
-
type ${componentName}Params = ${requestBodyComponent}
|
|
300
|
-
|
|
301
|
-
const ${fetchName} = async (body: ${componentName}Params) => {
|
|
302
|
-
const result = await api.${verb}<${responseTypes}>(\`${route}\`, body)
|
|
303
|
-
return result.data
|
|
304
|
-
}
|
|
305
|
-
`;
|
|
306
|
-
}
|
|
307
|
-
if (requestBodyComponent && !paramsInPath.length && queryParam && !headerParam) {
|
|
308
|
-
const config = isUpdateRequest ? 'null,{headers, params: queryParams}' : '{headers, params: queryParams}';
|
|
309
|
-
const queryParamsProps = queryParams.map((item) => `["${item.name}"]: props["${item.name}"]`);
|
|
310
|
-
output += `
|
|
311
|
-
type ${componentName}Params = ${requestBodyComponent} & {
|
|
312
|
-
${queryParamsType}
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
type ${componentName}QueryProps<T = ${responseTypes}> = ${componentName}Params & {
|
|
316
|
-
const body = {${generateBodyProps()}}
|
|
317
|
-
const params = {${generateProps(queryParams)}}
|
|
318
|
-
options?: UseQueryOptions<${responseTypes}, AxiosError, T, any>
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
const ${fetchName} = async ({body, params}: ${componentName}Params) => {
|
|
322
|
-
const queryParams = {${queryParamsProps.join(',')}}
|
|
323
|
-
const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config})
|
|
324
|
-
return result.data
|
|
325
|
-
}
|
|
326
|
-
`;
|
|
327
|
-
}
|
|
328
|
-
if (requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
|
|
329
|
-
output += `
|
|
330
|
-
type ${componentName}Params = ${requestBodyComponent} & {
|
|
331
|
-
${headerParam}
|
|
332
|
-
};
|
|
333
|
-
|
|
334
|
-
const ${fetchName} = async (props: ${componentName}Params) => {
|
|
335
|
-
const headers = {${generateProps(header)}}
|
|
336
|
-
const body = {${generateBodyProps()}}
|
|
337
|
-
const result = await api.${verb}<${responseTypes}>(\`${route}\`, body, {headers})
|
|
338
|
-
return result.data
|
|
339
|
-
}
|
|
340
|
-
`;
|
|
341
|
-
}
|
|
342
|
-
if (requestBodyComponent && !paramsInPath.length && queryParam && headerParam) {
|
|
343
|
-
output += `
|
|
344
|
-
type ${componentName}Params = ${requestBodyComponent} & {
|
|
345
|
-
${headerParam}
|
|
346
|
-
${paramsTypes}
|
|
347
|
-
};
|
|
348
|
-
|
|
349
|
-
const ${fetchName} = async (props: ${componentName}Params) => {
|
|
350
|
-
const body = {${generateBodyProps()}}
|
|
351
|
-
const headers = {${generateProps(header)}}
|
|
352
|
-
const params = {${generateProps(queryParams)}}
|
|
353
|
-
const result = await api.${verb}<${responseTypes}>(\`${route}\`, body, {headers, params})
|
|
354
|
-
return result.data
|
|
355
|
-
}
|
|
356
|
-
`;
|
|
357
|
-
}
|
|
358
|
-
if (requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
|
|
359
|
-
output += `
|
|
360
|
-
type ${componentName}Params = ${requestBodyComponent} & {
|
|
361
|
-
${headerParam}
|
|
362
|
-
${paramsTypes}
|
|
363
|
-
};
|
|
364
|
-
|
|
365
|
-
const ${fetchName} = async (props: ${componentName}Params) => {
|
|
366
|
-
const body = {${generateBodyProps()}}
|
|
367
|
-
const result = await api.${verb}<${responseTypes}>(\`${route.replace(/\{/g, '{props.')}\`, body)
|
|
368
|
-
return result.data
|
|
369
|
-
}
|
|
370
|
-
`;
|
|
371
|
-
}
|
|
372
|
-
if (requestBodyComponent && paramsInPath.length && queryParam && !headerParam) {
|
|
373
|
-
output += `// TODO: NOT SUPPORTED requestBodyComponent && paramsInPath && queryParam)`;
|
|
374
|
-
}
|
|
375
|
-
if (requestBodyComponent && paramsInPath.length && queryParam && headerParam) {
|
|
376
|
-
output += `// TODO: NOT SUPPORTED requestBodyComponent && paramsInPath && queryParam && headerParam)`;
|
|
377
|
-
}
|
|
378
|
-
if (!requestBodyComponent && paramsInPath.length && !queryParam && headerParam) {
|
|
379
|
-
const config = isUpdateRequest ? 'null,{headers}' : '{headers}';
|
|
380
|
-
output += `
|
|
381
|
-
type ${componentName}Params = {
|
|
382
|
-
${headerParam}
|
|
383
|
-
${paramsTypes}
|
|
384
|
-
};
|
|
385
|
-
|
|
386
|
-
const ${fetchName} = async (props: ${componentName}Params) => {
|
|
387
|
-
const headers = {${generateProps(header)}}
|
|
388
|
-
const result = await api.${verb}<${responseTypes}>(\`${route.replace(/\{/g, '{props.')}\`, ${config})
|
|
389
|
-
return result.data
|
|
390
|
-
}
|
|
391
|
-
`;
|
|
392
|
-
}
|
|
393
|
-
if (!requestBodyComponent && paramsInPath.length && queryParam && headerParam) {
|
|
394
|
-
output += `// TODO: NOT SUPPORTED (paramsInPath && queryParam && headerParam)`;
|
|
395
|
-
}
|
|
396
|
-
if (requestBodyComponent && paramsInPath.length && !queryParam && headerParam) {
|
|
397
|
-
output += `// TODO: NOT SUPPORTED (requestBodyComponent && paramsInPath && headerParam)`;
|
|
398
|
-
}
|
|
399
|
-
return { implementation: output, imports, queryImports };
|
|
400
|
-
};
|
|
401
|
-
exports.createHook = createHook;
|
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.generateImports = void 0;
|
|
4
|
-
const generateImports = ({ schemaName, apiDirectory, queryClientDir, schemaImports, queryImports, }) => {
|
|
5
|
-
const importTypes = schemaImports.join(',');
|
|
6
|
-
let imports = [];
|
|
7
|
-
if (queryImports.includes('query')) {
|
|
8
|
-
imports = [...imports, 'useQuery', 'UseQueryOptions', 'QueryKey', 'SetDataOptions', 'QueryFilters'];
|
|
9
|
-
}
|
|
10
|
-
if (queryImports.includes('infiniteQuery')) {
|
|
11
|
-
imports = [...imports, 'useInfiniteQuery', 'UseInfiniteQueryOptions', 'QueryKey'];
|
|
12
|
-
}
|
|
13
|
-
if (queryImports.includes('mutation')) {
|
|
14
|
-
imports = [...imports, 'UseMutationOptions', 'useMutation'];
|
|
15
|
-
}
|
|
16
|
-
const importString = [...new Set(imports)].join(',');
|
|
17
|
-
return `
|
|
18
|
-
import {
|
|
19
|
-
${importString}
|
|
20
|
-
} from '@tanstack/react-query';
|
|
21
|
-
|
|
22
|
-
import { AxiosError } from 'axios';
|
|
23
|
-
import { api } from '${apiDirectory}';
|
|
24
|
-
import { queryClient } from '${queryClientDir}';
|
|
25
|
-
|
|
26
|
-
import {${importTypes}} from './${schemaName}'
|
|
27
|
-
|
|
28
|
-
type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput);
|
|
29
|
-
`;
|
|
30
|
-
};
|
|
31
|
-
exports.generateImports = generateImports;
|
|
@@ -1,36 +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.generateRequestBodiesDefinition = void 0;
|
|
7
|
-
const case_1 = require("case");
|
|
8
|
-
const isEmpty_1 = __importDefault(require("lodash/isEmpty"));
|
|
9
|
-
const getResReqTypes_1 = require("./getResReqTypes");
|
|
10
|
-
/**
|
|
11
|
-
* Extract all types from #/components/requestBodies
|
|
12
|
-
*/
|
|
13
|
-
const generateRequestBodiesDefinition = (requestBodies = {}) => {
|
|
14
|
-
if ((0, isEmpty_1.default)(requestBodies)) {
|
|
15
|
-
return '';
|
|
16
|
-
}
|
|
17
|
-
return ('\n // REQUEST BODIES \n' +
|
|
18
|
-
Object.entries(requestBodies)
|
|
19
|
-
.map(([name, requestBody]) => {
|
|
20
|
-
const doc = (0, getResReqTypes_1.getDocs)(requestBody);
|
|
21
|
-
const type = (0, getResReqTypes_1.getResReqTypes)([['', requestBody]]);
|
|
22
|
-
const isEmptyInterface = type === '{}';
|
|
23
|
-
if (isEmptyInterface) {
|
|
24
|
-
return `export type ${(0, case_1.pascal)(name)}RequestBody = ${type}`;
|
|
25
|
-
}
|
|
26
|
-
else if (type.includes('{') && !type.includes('|') && !type.includes('&')) {
|
|
27
|
-
return `${doc}export type ${(0, case_1.pascal)(name)}RequestBody = ${type}`;
|
|
28
|
-
}
|
|
29
|
-
else {
|
|
30
|
-
return `${doc}export type ${(0, case_1.pascal)(name)}RequestBody = ${type};`;
|
|
31
|
-
}
|
|
32
|
-
})
|
|
33
|
-
.join('\n\n') +
|
|
34
|
-
'\n');
|
|
35
|
-
};
|
|
36
|
-
exports.generateRequestBodiesDefinition = generateRequestBodiesDefinition;
|