react-query-lightbase-codegen 0.3.0 → 0.5.0
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/lib/cjs/convertSwaggerFile.js +32 -0
- package/lib/cjs/generateHooks.js +401 -0
- package/lib/cjs/generateImports.js +31 -0
- package/lib/cjs/generateRequestBodiesDefinition.js +36 -0
- package/lib/cjs/generateResponsesDefinition.js +36 -0
- package/lib/cjs/generateSchemas.js +103 -0
- package/lib/cjs/generateSchemasDefinition.js +40 -0
- package/lib/cjs/getResReqTypes.js +162 -0
- package/lib/cjs/import-open-api.js +10 -1005
- package/lib/cjs/importSpecs.js +87 -0
- package/lib/cjs/index.js +5 -3
- package/lib/cjs/react-query-codegen-import.js +20 -12
- package/lib/cjs/resolveDiscriminator.js +31 -0
- package/lib/cjs/utils.js +168 -0
- package/lib/esm/convertSwaggerFile.js +25 -0
- package/lib/esm/generateHooks.js +394 -0
- package/lib/esm/generateImports.js +27 -0
- package/lib/esm/generateRequestBodiesDefinition.js +29 -0
- package/lib/esm/generateResponsesDefinition.js +29 -0
- package/lib/esm/generateSchemas.js +96 -0
- package/lib/esm/generateSchemasDefinition.js +33 -0
- package/lib/esm/getResReqTypes.js +150 -0
- package/lib/esm/import-open-api.js +8 -988
- package/lib/esm/importSpecs.js +80 -0
- package/lib/esm/index.js +3 -2
- package/lib/esm/react-query-codegen-import.js +21 -13
- package/lib/esm/resolveDiscriminator.js +24 -0
- package/lib/esm/utils.js +156 -0
- package/package.json +17 -15
|
@@ -0,0 +1,32 @@
|
|
|
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;
|
|
@@ -0,0 +1,401 @@
|
|
|
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;
|
|
@@ -0,0 +1,31 @@
|
|
|
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;
|
|
@@ -0,0 +1,36 @@
|
|
|
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;
|
|
@@ -0,0 +1,36 @@
|
|
|
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.generateResponsesDefinition = 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/responses
|
|
12
|
+
*/
|
|
13
|
+
const generateResponsesDefinition = (responses = {}) => {
|
|
14
|
+
if ((0, isEmpty_1.default)(responses)) {
|
|
15
|
+
return '';
|
|
16
|
+
}
|
|
17
|
+
return ('\n // RESPONSES \n' +
|
|
18
|
+
Object.entries(responses)
|
|
19
|
+
.map(([name, response]) => {
|
|
20
|
+
const doc = (0, getResReqTypes_1.getDocs)(response);
|
|
21
|
+
const type = (0, getResReqTypes_1.getResReqTypes)([['', response]]);
|
|
22
|
+
const isEmptyInterface = type === '{}';
|
|
23
|
+
if (isEmptyInterface) {
|
|
24
|
+
return `export type RQ${(0, case_1.pascal)(name)}Response = ${type}`;
|
|
25
|
+
}
|
|
26
|
+
else if (type.includes('{') && !type.includes('|') && !type.includes('&')) {
|
|
27
|
+
return `${doc}export type RQ${(0, case_1.pascal)(name)}Response = ${type}`;
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
return `${doc}export type RQ${(0, case_1.pascal)(name)}Response = ${type};`;
|
|
31
|
+
}
|
|
32
|
+
})
|
|
33
|
+
.join('\n\n') +
|
|
34
|
+
'\n');
|
|
35
|
+
};
|
|
36
|
+
exports.generateResponsesDefinition = generateResponsesDefinition;
|
|
@@ -0,0 +1,103 @@
|
|
|
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.generateSchemas = void 0;
|
|
7
|
+
const case_1 = __importDefault(require("case"));
|
|
8
|
+
const lodash_1 = __importDefault(require("lodash"));
|
|
9
|
+
const { isEmpty } = lodash_1.default;
|
|
10
|
+
const { pascal } = case_1.default;
|
|
11
|
+
const utils_js_1 = require("./utils.js");
|
|
12
|
+
const utils_js_2 = require("./utils.js");
|
|
13
|
+
/**
|
|
14
|
+
* Generate the interface string
|
|
15
|
+
*/
|
|
16
|
+
const generateInterface = (name, schema) => {
|
|
17
|
+
const scalar = (0, utils_js_1.getScalar)(schema);
|
|
18
|
+
return `${(0, utils_js_1.formatDescription)(schema.description)}
|
|
19
|
+
export type ${pascal(name)} = ${scalar}
|
|
20
|
+
`;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Extract all types from #/components/schemas
|
|
24
|
+
*/
|
|
25
|
+
const generateSchemasDefinition = (schemas = {}) => {
|
|
26
|
+
if (isEmpty(schemas)) {
|
|
27
|
+
return '';
|
|
28
|
+
}
|
|
29
|
+
return ('\n // SCEHMAS \n' +
|
|
30
|
+
Object.entries(schemas)
|
|
31
|
+
.map(([name, schema]) => !(0, utils_js_1.isReference)(schema) &&
|
|
32
|
+
(!schema.type || schema.type === 'object') &&
|
|
33
|
+
!schema.allOf &&
|
|
34
|
+
!schema.oneOf &&
|
|
35
|
+
!(0, utils_js_1.isReference)(schema) &&
|
|
36
|
+
!schema.nullable
|
|
37
|
+
? generateInterface(name, schema)
|
|
38
|
+
: `${(0, utils_js_1.formatDescription)((0, utils_js_1.isReference)(schema) ? undefined : schema.description)} export type ${pascal(name)} = ${(0, utils_js_1.resolveValue)(schema)};`)
|
|
39
|
+
.join('\n\n') +
|
|
40
|
+
'\n');
|
|
41
|
+
};
|
|
42
|
+
/**
|
|
43
|
+
* Extract all types from #/components/requestBodies
|
|
44
|
+
*/
|
|
45
|
+
const generateRequestBodiesDefinition = (requestBodies = {}) => {
|
|
46
|
+
if (isEmpty(requestBodies)) {
|
|
47
|
+
return '';
|
|
48
|
+
}
|
|
49
|
+
return ('\n // REQUEST BODIES \n' +
|
|
50
|
+
Object.entries(requestBodies)
|
|
51
|
+
.map(([name, requestBody]) => {
|
|
52
|
+
const doc = (0, utils_js_2.getDocs)(requestBody);
|
|
53
|
+
const type = (0, utils_js_2.getResReqTypes)([['', requestBody]]);
|
|
54
|
+
const isEmptyInterface = type === '{}';
|
|
55
|
+
if (isEmptyInterface) {
|
|
56
|
+
return `${doc}\nexport type ${pascal(name)}RequestBody = ${type}`;
|
|
57
|
+
}
|
|
58
|
+
else if (type.includes('{') && !type.includes('|') && !type.includes('&')) {
|
|
59
|
+
return `${doc}\nexport type ${pascal(name)}RequestBody = ${type}`;
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
return `${doc}\nexport type ${pascal(name)}RequestBody = ${type};`;
|
|
63
|
+
}
|
|
64
|
+
})
|
|
65
|
+
.join('\n\n') +
|
|
66
|
+
'\n');
|
|
67
|
+
};
|
|
68
|
+
/**
|
|
69
|
+
* Extract all types from #/components/responses
|
|
70
|
+
*/
|
|
71
|
+
const generateResponsesDefinition = (responses = {}) => {
|
|
72
|
+
if (isEmpty(responses)) {
|
|
73
|
+
return '';
|
|
74
|
+
}
|
|
75
|
+
return ('\n // RESPONSES \n' +
|
|
76
|
+
Object.entries(responses)
|
|
77
|
+
.map(([name, response]) => {
|
|
78
|
+
const doc = (0, utils_js_2.getDocs)(response);
|
|
79
|
+
const type = (0, utils_js_2.getResReqTypes)([['', response]]);
|
|
80
|
+
const isEmptyInterface = type === '{}';
|
|
81
|
+
if (isEmptyInterface) {
|
|
82
|
+
return `export type RQ${pascal(name)}Response = ${type}`;
|
|
83
|
+
}
|
|
84
|
+
else if (type.includes('{') && !type.includes('|') && !type.includes('&')) {
|
|
85
|
+
return `${doc}export type RQ${pascal(name)}Response = ${type}`;
|
|
86
|
+
}
|
|
87
|
+
else {
|
|
88
|
+
return `${doc}export type RQ${pascal(name)}Response = ${type};`;
|
|
89
|
+
}
|
|
90
|
+
})
|
|
91
|
+
.join('\n\n') +
|
|
92
|
+
'\n');
|
|
93
|
+
};
|
|
94
|
+
/**
|
|
95
|
+
* Extract all types from #/components/schemas
|
|
96
|
+
*/
|
|
97
|
+
const generateSchemas = ({ spec }) => {
|
|
98
|
+
const schemaOutput = generateRequestBodiesDefinition(spec.components?.requestBodies) +
|
|
99
|
+
generateResponsesDefinition(spec.components?.responses) +
|
|
100
|
+
generateSchemasDefinition(spec.components?.schemas);
|
|
101
|
+
return schemaOutput;
|
|
102
|
+
};
|
|
103
|
+
exports.generateSchemas = generateSchemas;
|