react-query-lightbase-codegen 1.0.0 → 1.0.3
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/package.json +5 -4
- package/src/convertSwaggerFile.ts +25 -0
- package/src/generateHooks.ts +490 -0
- package/src/generateImports.ts +41 -0
- package/src/generateSchemas.ts +114 -0
- package/src/importSpecs.ts +110 -0
- package/{lib/esm/index.js → src/index.ts} +0 -0
- package/src/utils.ts +190 -0
- package/lib/cjs/convertSwaggerFile.js +0 -32
- package/lib/cjs/generateHooks.js +0 -401
- package/lib/cjs/generateImports.js +0 -31
- package/lib/cjs/generateSchemas.js +0 -103
- package/lib/cjs/importSpecs.js +0 -87
- package/lib/cjs/index.js +0 -7
- 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/generateSchemas.js +0 -96
- package/lib/esm/importSpecs.js +0 -80
- package/lib/esm/utils.js +0 -156
package/package.json
CHANGED
|
@@ -1,12 +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.0.
|
|
4
|
+
"version": "1.0.3",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
7
|
-
"exports": "./
|
|
7
|
+
"exports": "./dist/index.js",
|
|
8
8
|
"files": [
|
|
9
|
-
"
|
|
9
|
+
"src",
|
|
10
|
+
"dist"
|
|
10
11
|
],
|
|
11
12
|
"keywords": [
|
|
12
13
|
"rest",
|
|
@@ -35,7 +36,7 @@
|
|
|
35
36
|
},
|
|
36
37
|
"scripts": {
|
|
37
38
|
"lint": "eslint . --ext .js,.jsx,.ts,.tsx",
|
|
38
|
-
"tsc": "tsc -p tsconfig.json
|
|
39
|
+
"tsc": "tsc -p tsconfig.json",
|
|
39
40
|
"test": "yarn tsc && node test/script.mjs && prettier --check ./test/generated/**/*.tsx --write && eslint ./test/generated/**/*.tsx --fix",
|
|
40
41
|
"prepare": "husky install"
|
|
41
42
|
},
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { OpenAPIObject } from 'openapi3-ts';
|
|
2
|
+
import swagger2openapi from 'swagger2openapi';
|
|
3
|
+
import yaml from 'js-yaml';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Import and parse the openapi spec from a yaml/json
|
|
7
|
+
*/
|
|
8
|
+
export const convertSwaggerFile = (data: string, extension: 'yaml' | 'json'): Promise<OpenAPIObject> => {
|
|
9
|
+
const schema = extension === 'yaml' ? yaml.load(data) : JSON.parse(data);
|
|
10
|
+
return new Promise((resolve, reject) => {
|
|
11
|
+
if (!schema.openapi || !schema.openapi.startsWith('3.')) {
|
|
12
|
+
swagger2openapi.convertObj(schema, {}, (err, convertedObj) => {
|
|
13
|
+
if (err) {
|
|
14
|
+
reject(err);
|
|
15
|
+
} else {
|
|
16
|
+
// @ts-ignore
|
|
17
|
+
convertedObj.openapi.basePath = convertedObj.original.basePath;
|
|
18
|
+
resolve(convertedObj.openapi);
|
|
19
|
+
}
|
|
20
|
+
});
|
|
21
|
+
} else {
|
|
22
|
+
resolve(schema);
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
};
|
|
@@ -0,0 +1,490 @@
|
|
|
1
|
+
import lodash from 'lodash';
|
|
2
|
+
const { get, groupBy } = lodash;
|
|
3
|
+
import {
|
|
4
|
+
ComponentsObject,
|
|
5
|
+
OperationObject,
|
|
6
|
+
ParameterObject,
|
|
7
|
+
ReferenceObject,
|
|
8
|
+
ResponseObject,
|
|
9
|
+
SchemaObject,
|
|
10
|
+
} from 'openapi3-ts';
|
|
11
|
+
import { formatDescription, getResReqTypes, isReference, resolveValue } from './utils.js';
|
|
12
|
+
import pasCase from 'case';
|
|
13
|
+
import chalk from 'chalk';
|
|
14
|
+
|
|
15
|
+
const { pascal, camel } = pasCase;
|
|
16
|
+
|
|
17
|
+
const IdentifierRegexp = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Return every params in a path
|
|
21
|
+
*/
|
|
22
|
+
const getParamsInPath = (path: string) => {
|
|
23
|
+
let n;
|
|
24
|
+
const output = [];
|
|
25
|
+
const templatePathRegex = /\{(\w+)}/g;
|
|
26
|
+
while ((n = templatePathRegex.exec(path)) !== null) {
|
|
27
|
+
output.push(n[1]);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
return output;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Generate a react-query component from openapi operation specs
|
|
35
|
+
*/
|
|
36
|
+
export const createHook = ({
|
|
37
|
+
operation,
|
|
38
|
+
verb,
|
|
39
|
+
route,
|
|
40
|
+
operationIds,
|
|
41
|
+
parameters,
|
|
42
|
+
schemasComponents,
|
|
43
|
+
headerFilters,
|
|
44
|
+
overrides,
|
|
45
|
+
}: {
|
|
46
|
+
operation: OperationObject;
|
|
47
|
+
verb: string;
|
|
48
|
+
route: string;
|
|
49
|
+
operationIds: string[];
|
|
50
|
+
parameters: (ReferenceObject | ParameterObject)[] | undefined;
|
|
51
|
+
schemasComponents?: ComponentsObject;
|
|
52
|
+
headerFilters?: string[];
|
|
53
|
+
overrides?: Record<
|
|
54
|
+
string,
|
|
55
|
+
{ type: 'query' } | { type: 'mutation' } | { type: 'infiniteQuery'; infiniteQueryParm: string }
|
|
56
|
+
>;
|
|
57
|
+
}) => {
|
|
58
|
+
const { operationId = route.replace('/', '') } = operation;
|
|
59
|
+
if (operationId === '*') {
|
|
60
|
+
throw new Error(`Invalid operationId/Route set for ${verb} ${route}`);
|
|
61
|
+
}
|
|
62
|
+
if (operationIds.includes(operationId)) {
|
|
63
|
+
return { implementation: '', imports: [], queryImports: [] };
|
|
64
|
+
}
|
|
65
|
+
operationIds.push(operationId);
|
|
66
|
+
|
|
67
|
+
route = route.replace(/\{/g, '${').replace('//', '/'); // `/pet/{id}` => `/pet/${id}`
|
|
68
|
+
|
|
69
|
+
// Remove the last param of the route if we are in the DELETE case
|
|
70
|
+
let lastParamInTheRoute: string | null = null;
|
|
71
|
+
|
|
72
|
+
const componentName = pascal(operationId!);
|
|
73
|
+
|
|
74
|
+
const isOk = ([statusCode]: [string, ResponseObject | ReferenceObject]) =>
|
|
75
|
+
statusCode.toString().startsWith('2');
|
|
76
|
+
|
|
77
|
+
const responseTypes = getResReqTypes(Object.entries(operation.responses).filter(isOk)) || 'void';
|
|
78
|
+
const requestBodyTypes = getResReqTypes([['body', operation.requestBody!]]);
|
|
79
|
+
|
|
80
|
+
let imports = [responseTypes];
|
|
81
|
+
let queryImports = [] as Array<'mutation' | 'query' | 'infiniteQuery'>;
|
|
82
|
+
|
|
83
|
+
const paramsInPath = getParamsInPath(route).filter(
|
|
84
|
+
(param) => !(verb === 'delete' && param === lastParamInTheRoute)
|
|
85
|
+
);
|
|
86
|
+
|
|
87
|
+
const {
|
|
88
|
+
query: queryParams = [],
|
|
89
|
+
path: pathParams = [],
|
|
90
|
+
header = [],
|
|
91
|
+
} = groupBy(
|
|
92
|
+
[...(parameters || []), ...(operation.parameters || [])].map<ParameterObject>((p) => {
|
|
93
|
+
if (isReference(p)) {
|
|
94
|
+
return get(schemasComponents, p.$ref.replace('#/components/', '').replace('/', '.'));
|
|
95
|
+
} else {
|
|
96
|
+
return p;
|
|
97
|
+
}
|
|
98
|
+
}),
|
|
99
|
+
'in'
|
|
100
|
+
);
|
|
101
|
+
|
|
102
|
+
const headerParams = header.filter((p) => !headerFilters?.includes(p.name));
|
|
103
|
+
|
|
104
|
+
let enabled = [] as any;
|
|
105
|
+
|
|
106
|
+
// TODO: extract all requestBody or remove useQuery variants
|
|
107
|
+
let enabledParam = '!!params';
|
|
108
|
+
[...queryParams, ...pathParams, ...headerParams].forEach((item) => {
|
|
109
|
+
if (item.required) {
|
|
110
|
+
enabled.push(`["${item.name}"]`);
|
|
111
|
+
if (enabledParam && enabledParam !== '!!params') {
|
|
112
|
+
enabledParam += `&& params['${item.name}'] != null`;
|
|
113
|
+
} else {
|
|
114
|
+
enabledParam = `params['${item.name}'] != null`;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
// `!props${enabled.join('== null && !props')}`;
|
|
120
|
+
|
|
121
|
+
const paramsTypes = paramsInPath
|
|
122
|
+
.map((p) => {
|
|
123
|
+
try {
|
|
124
|
+
const { name, required, schema } = pathParams.find((i) => i.name === p)!;
|
|
125
|
+
return `${name}${required ? '' : '?'}: ${resolveValue(schema!)}`;
|
|
126
|
+
} catch (err) {
|
|
127
|
+
throw new Error(`The path params ${p} can't be found in parameters (${operationId})`);
|
|
128
|
+
}
|
|
129
|
+
})
|
|
130
|
+
.join('; ');
|
|
131
|
+
|
|
132
|
+
const queryParamsType = queryParams
|
|
133
|
+
.map((p) => {
|
|
134
|
+
const processedName = IdentifierRegexp.test(p.name) ? p.name : `"${p.name}"`;
|
|
135
|
+
return `${formatDescription(p.description)}
|
|
136
|
+
${processedName}${p.required ? '' : '?'}: ${resolveValue(p.schema!)}`;
|
|
137
|
+
})
|
|
138
|
+
.join(';\n ');
|
|
139
|
+
|
|
140
|
+
const headerType = headerParams
|
|
141
|
+
.map((p) => {
|
|
142
|
+
try {
|
|
143
|
+
const { name, required, schema } = headerParams.find((i) => i.name === p.name)!;
|
|
144
|
+
return `"${name}"${required ? '' : '?'}: ${resolveValue(schema!)}`;
|
|
145
|
+
} catch (err) {
|
|
146
|
+
throw new Error(`The path params ${p} can't be found in parameters (${operationId})`);
|
|
147
|
+
}
|
|
148
|
+
})
|
|
149
|
+
.join('; ');
|
|
150
|
+
|
|
151
|
+
// Retrieve the type of the param for delete verb
|
|
152
|
+
const lastParamInTheRouteDefinition =
|
|
153
|
+
operation.parameters && lastParamInTheRoute
|
|
154
|
+
? (operation.parameters.find((p) => {
|
|
155
|
+
if (isReference(p)) {
|
|
156
|
+
return false;
|
|
157
|
+
}
|
|
158
|
+
return p.name === lastParamInTheRoute;
|
|
159
|
+
}) as ParameterObject | undefined) // Reference is not possible
|
|
160
|
+
: { schema: { type: 'string' } };
|
|
161
|
+
|
|
162
|
+
if (!lastParamInTheRouteDefinition) {
|
|
163
|
+
throw new Error(`The path params ${lastParamInTheRoute} can't be found in parameters (${operationId})`);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const defaultDescription = `type: ${verb}\noperationId: ${operationId}\nurl: ${route}`;
|
|
167
|
+
|
|
168
|
+
const description = formatDescription(
|
|
169
|
+
operation.summary && operation.description
|
|
170
|
+
? `${defaultDescription}\n\n${operation.summary}\n\n${operation.description}`
|
|
171
|
+
: `${defaultDescription}`
|
|
172
|
+
);
|
|
173
|
+
|
|
174
|
+
let output = `\n\n${description}`;
|
|
175
|
+
|
|
176
|
+
const headerParam = headerType && headerType !== 'void' ? `${headerType};` : '';
|
|
177
|
+
const queryParam = queryParamsType && queryParamsType !== 'void' ? `${queryParamsType}` : '';
|
|
178
|
+
const requestBodyComponent = requestBodyTypes && requestBodyTypes !== 'void' ? `${requestBodyTypes}` : '';
|
|
179
|
+
|
|
180
|
+
if (requestBodyComponent) {
|
|
181
|
+
imports.push(requestBodyComponent);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const isUpdateRequest = ['post', 'patch', 'put'].includes(verb);
|
|
185
|
+
|
|
186
|
+
const generateProps = (props: ParameterObject[]) => {
|
|
187
|
+
return props.map((item) => `["${item.name}"]: props["${item.name}"]`).join(',');
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
const generateBodyProps = () => {
|
|
191
|
+
const definitionKey = Object.keys(schemasComponents?.schemas || {}).find(
|
|
192
|
+
(key) => pascal(key) === requestBodyComponent
|
|
193
|
+
);
|
|
194
|
+
if (definitionKey) {
|
|
195
|
+
const scheme = schemasComponents?.schemas?.[definitionKey] as SchemaObject;
|
|
196
|
+
return Object.keys(scheme.properties as SchemaObject)
|
|
197
|
+
.map((item: string) => `["${item}"]: props["${item}"]`)
|
|
198
|
+
.join(',');
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
const fetchName = camel(componentName);
|
|
203
|
+
|
|
204
|
+
const createQueryHooks = (emptyParams?: boolean) => {
|
|
205
|
+
const params = emptyParams ? '' : `params: ${componentName}Params,`;
|
|
206
|
+
const key = emptyParams ? '' : `params`;
|
|
207
|
+
const mutationParams = emptyParams ? 'void' : `${componentName}Params`;
|
|
208
|
+
const queryParamType = emptyParams ? '' : `${componentName}Params &`;
|
|
209
|
+
const filterParams = emptyParams
|
|
210
|
+
? '{ filters }: { filters?: QueryFilters }'
|
|
211
|
+
: `{ params, filters }: { params: ${componentName}Params, filters?: QueryFilters }`;
|
|
212
|
+
const cacheParams = emptyParams
|
|
213
|
+
? `{updater, options}: {updater: Updater<${responseTypes} | undefined, ${responseTypes} | undefined>, options?: SetDataOptions | undefined}`
|
|
214
|
+
: `{params, updater, options}: {params: ${componentName}Params, updater: Updater<${responseTypes} | undefined, ${responseTypes} | undefined>, options?: SetDataOptions | undefined}`;
|
|
215
|
+
const queryKey = emptyParams
|
|
216
|
+
? `use${componentName}Query.baseKey()`
|
|
217
|
+
: `[...use${componentName}Query.baseKey(), params]`;
|
|
218
|
+
|
|
219
|
+
const createQuery = () => `
|
|
220
|
+
type ${componentName}QueryProps<T = ${responseTypes}> = ${queryParamType} {
|
|
221
|
+
options?: UseQueryOptions<${responseTypes}, AxiosError, T, any>
|
|
222
|
+
}
|
|
223
|
+
export function use${componentName}Query<T = ${responseTypes}>({ options = {}, ...params }: ${componentName}QueryProps<T>) {
|
|
224
|
+
return useQuery(use${componentName}Query.queryKey(${key}), async () => ${fetchName}(${key}), { enabled: ${enabledParam}, ...options });
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
|
|
228
|
+
|
|
229
|
+
use${componentName}Query.queryKey = (${params}): QueryKey => ${queryKey};
|
|
230
|
+
|
|
231
|
+
use${componentName}Query.updateCache = (${cacheParams}) => queryClient.setQueryData<${responseTypes}>(use${componentName}Query.queryKey(${key}), updater, options);
|
|
232
|
+
|
|
233
|
+
use${componentName}Query.getQueryState = (${filterParams})=> queryClient.getQueryState<${responseTypes}>(use${componentName}Query.queryKey(${key}), filters);
|
|
234
|
+
|
|
235
|
+
use${componentName}Query.getQueryData = (${filterParams})=> queryClient.getQueryData<${responseTypes}>(use${componentName}Query.queryKey(${key}), filters);
|
|
236
|
+
|
|
237
|
+
use${componentName}Query.prefetch = (${params}) => queryClient.prefetchQuery<${responseTypes}>(use${componentName}Query.queryKey(${key}), ()=> ${fetchName}(${key}));
|
|
238
|
+
|
|
239
|
+
use${componentName}Query.cancelQueries = (${params}) => queryClient.cancelQueries(use${componentName}Query.queryKey(${key}))
|
|
240
|
+
|
|
241
|
+
use${componentName}Query.invalidate = (${params}) => queryClient.invalidateQueries<${responseTypes}>(use${componentName}Query.queryKey(${key}));
|
|
242
|
+
|
|
243
|
+
use${componentName}Query.refetchStale = (${params}) => queryClient.refetchQueries<${responseTypes}>(use${componentName}Query.queryKey(${key}), { stale: true });
|
|
244
|
+
`;
|
|
245
|
+
|
|
246
|
+
const getInfiniteQuery = ({ pageParam }: { pageParam: string }) => `
|
|
247
|
+
type ${componentName}QueryProps<T = ${responseTypes}> = ${queryParamType} {
|
|
248
|
+
options: UseInfiniteQueryOptions<${responseTypes}, AxiosError, T, any>
|
|
249
|
+
}
|
|
250
|
+
export function use${componentName}Query<T = ${responseTypes}>({ options = {}, ...params }: ${componentName}QueryProps<T>) {
|
|
251
|
+
return useInfiniteQuery(use${componentName}Query.queryKey(${key}), async ({ pageParam = 0 }) => ${fetchName}({${pageParam}: pageParam, ...params}), { enabled: ${enabledParam}, ...options });
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
|
|
255
|
+
|
|
256
|
+
use${componentName}Query.queryKey = (${params}): QueryKey => ${queryKey};
|
|
257
|
+
|
|
258
|
+
`;
|
|
259
|
+
|
|
260
|
+
const createMutation = () => `
|
|
261
|
+
type ${componentName}MutationProps<T> = {
|
|
262
|
+
options?: UseMutationOptions<${responseTypes}, AxiosError, ${mutationParams}, T>
|
|
263
|
+
}
|
|
264
|
+
export function use${componentName}Mutation<T = ${responseTypes}>(props?: ${componentName}MutationProps<T>) {
|
|
265
|
+
return useMutation(async (${key}) => ${fetchName}(${key}), props?.options)
|
|
266
|
+
};
|
|
267
|
+
`;
|
|
268
|
+
|
|
269
|
+
const override = overrides?.[operationId];
|
|
270
|
+
if (override?.type === 'query') {
|
|
271
|
+
console.log(chalk.blue(`⚙️ [${operationId}] has been changed to a useQuery hook`));
|
|
272
|
+
queryImports.push('query');
|
|
273
|
+
return createQuery();
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
if (override?.type === 'mutation') {
|
|
277
|
+
queryImports.push('mutation');
|
|
278
|
+
console.log(chalk.blue(`⚙️ [${operationId}] has been changed to a useMutation hook`));
|
|
279
|
+
return createMutation();
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
if (override?.type === 'infiniteQuery') {
|
|
283
|
+
console.log(chalk.blue(`⚙️ [${operationId}] has been changed to a useInfiniteQuery hook`));
|
|
284
|
+
queryImports.push('infiniteQuery');
|
|
285
|
+
return getInfiniteQuery({ pageParam: override.infiniteQueryParm });
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
if (verb === 'get') {
|
|
289
|
+
queryImports.push('query');
|
|
290
|
+
return createQuery();
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
queryImports.push('mutation');
|
|
294
|
+
return createMutation();
|
|
295
|
+
};
|
|
296
|
+
|
|
297
|
+
output += createQueryHooks(!requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam);
|
|
298
|
+
|
|
299
|
+
if (!requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
|
|
300
|
+
output += `
|
|
301
|
+
const ${fetchName} = async () => {
|
|
302
|
+
const result = await api.${verb}<${responseTypes}>(\`${route}\`);
|
|
303
|
+
return result.data;
|
|
304
|
+
}
|
|
305
|
+
`;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
if (!requestBodyComponent && paramsInPath.length && queryParam && !headerParam) {
|
|
309
|
+
const config = isUpdateRequest ? 'body,{params}' : '{params}';
|
|
310
|
+
output += `
|
|
311
|
+
type ${componentName}Params = {
|
|
312
|
+
${paramsTypes}
|
|
313
|
+
${queryParamsType};
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
const ${fetchName} = async (props:${componentName}Params) => {
|
|
317
|
+
const {${paramsInPath.join(', ')}, ...params} = props
|
|
318
|
+
const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config})
|
|
319
|
+
return result.data;
|
|
320
|
+
}`;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
if (!requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
|
|
324
|
+
output += `
|
|
325
|
+
type ${componentName}Params = {
|
|
326
|
+
${paramsTypes}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
const ${fetchName} = async (props: ${componentName}Params ) => {
|
|
330
|
+
const result = await api.${verb}<${responseTypes}>(\`${route.replace(/\{/g, '{props.')}\`);
|
|
331
|
+
return result.data;
|
|
332
|
+
}
|
|
333
|
+
`;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
if (!requestBodyComponent && !paramsInPath.length && queryParam && !headerParam) {
|
|
337
|
+
const config = isUpdateRequest ? 'null,{params}' : '{params}';
|
|
338
|
+
output += `
|
|
339
|
+
type ${componentName}Params = {
|
|
340
|
+
${queryParamsType}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
const ${fetchName} = async (params: ${componentName}Params) => {
|
|
344
|
+
const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config})
|
|
345
|
+
return result.data;
|
|
346
|
+
}
|
|
347
|
+
`;
|
|
348
|
+
}
|
|
349
|
+
if (!requestBodyComponent && !paramsInPath.length && queryParam && headerParam) {
|
|
350
|
+
const config = isUpdateRequest ? 'null,{headers, params: queryParams}' : '{headers, params: queryParams}';
|
|
351
|
+
output += `
|
|
352
|
+
type ${componentName}Params = {
|
|
353
|
+
${headerParam}
|
|
354
|
+
${queryParamsType}
|
|
355
|
+
}
|
|
356
|
+
const ${fetchName} = async (props: ${componentName}Params) => {
|
|
357
|
+
const headers = {${generateProps(header)}}
|
|
358
|
+
const queryParams = {${generateProps(queryParams)}}
|
|
359
|
+
const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config})
|
|
360
|
+
return result.data
|
|
361
|
+
}`;
|
|
362
|
+
}
|
|
363
|
+
if (!requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
|
|
364
|
+
const config = isUpdateRequest ? 'null,{headers}' : '{headers}';
|
|
365
|
+
output += `
|
|
366
|
+
type ${componentName}Params = {
|
|
367
|
+
${headerParam}
|
|
368
|
+
};
|
|
369
|
+
|
|
370
|
+
const ${fetchName} = async (headers: ${componentName}Params) => {
|
|
371
|
+
const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config});
|
|
372
|
+
return result.data;
|
|
373
|
+
}
|
|
374
|
+
`;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
if (requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
|
|
378
|
+
output += `
|
|
379
|
+
type ${componentName}Params = ${requestBodyComponent}
|
|
380
|
+
|
|
381
|
+
const ${fetchName} = async (body: ${componentName}Params) => {
|
|
382
|
+
const result = await api.${verb}<${responseTypes}>(\`${route}\`, body)
|
|
383
|
+
return result.data
|
|
384
|
+
}
|
|
385
|
+
`;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
if (requestBodyComponent && !paramsInPath.length && queryParam && !headerParam) {
|
|
389
|
+
const config = isUpdateRequest ? 'null,{headers, params: queryParams}' : '{headers, params: queryParams}';
|
|
390
|
+
const queryParamsProps = queryParams.map((item) => `["${item.name}"]: props["${item.name}"]`);
|
|
391
|
+
output += `
|
|
392
|
+
type ${componentName}Params = ${requestBodyComponent} & {
|
|
393
|
+
${queryParamsType}
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
type ${componentName}QueryProps<T = ${responseTypes}> = ${componentName}Params & {
|
|
397
|
+
const body = {${generateBodyProps()}}
|
|
398
|
+
const params = {${generateProps(queryParams)}}
|
|
399
|
+
options?: UseQueryOptions<${responseTypes}, AxiosError, T, any>
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
const ${fetchName} = async ({body, params}: ${componentName}Params) => {
|
|
403
|
+
const queryParams = {${queryParamsProps.join(',')}}
|
|
404
|
+
const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config})
|
|
405
|
+
return result.data
|
|
406
|
+
}
|
|
407
|
+
`;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
if (requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
|
|
411
|
+
output += `
|
|
412
|
+
type ${componentName}Params = ${requestBodyComponent} & {
|
|
413
|
+
${headerParam}
|
|
414
|
+
};
|
|
415
|
+
|
|
416
|
+
const ${fetchName} = async (props: ${componentName}Params) => {
|
|
417
|
+
const headers = {${generateProps(header)}}
|
|
418
|
+
const body = {${generateBodyProps()}}
|
|
419
|
+
const result = await api.${verb}<${responseTypes}>(\`${route}\`, body, {headers})
|
|
420
|
+
return result.data
|
|
421
|
+
}
|
|
422
|
+
`;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
if (requestBodyComponent && !paramsInPath.length && queryParam && headerParam) {
|
|
426
|
+
output += `
|
|
427
|
+
type ${componentName}Params = ${requestBodyComponent} & {
|
|
428
|
+
${headerParam}
|
|
429
|
+
${paramsTypes}
|
|
430
|
+
};
|
|
431
|
+
|
|
432
|
+
const ${fetchName} = async (props: ${componentName}Params) => {
|
|
433
|
+
const body = {${generateBodyProps()}}
|
|
434
|
+
const headers = {${generateProps(header)}}
|
|
435
|
+
const params = {${generateProps(queryParams)}}
|
|
436
|
+
const result = await api.${verb}<${responseTypes}>(\`${route}\`, body, {headers, params})
|
|
437
|
+
return result.data
|
|
438
|
+
}
|
|
439
|
+
`;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
if (requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
|
|
443
|
+
output += `
|
|
444
|
+
type ${componentName}Params = ${requestBodyComponent} & {
|
|
445
|
+
${headerParam}
|
|
446
|
+
${paramsTypes}
|
|
447
|
+
};
|
|
448
|
+
|
|
449
|
+
const ${fetchName} = async (props: ${componentName}Params) => {
|
|
450
|
+
const body = {${generateBodyProps()}}
|
|
451
|
+
const result = await api.${verb}<${responseTypes}>(\`${route.replace(/\{/g, '{props.')}\`, body)
|
|
452
|
+
return result.data
|
|
453
|
+
}
|
|
454
|
+
`;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
if (requestBodyComponent && paramsInPath.length && queryParam && !headerParam) {
|
|
458
|
+
output += `// TODO: NOT SUPPORTED requestBodyComponent && paramsInPath && queryParam)`;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
if (requestBodyComponent && paramsInPath.length && queryParam && headerParam) {
|
|
462
|
+
output += `// TODO: NOT SUPPORTED requestBodyComponent && paramsInPath && queryParam && headerParam)`;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
if (!requestBodyComponent && paramsInPath.length && !queryParam && headerParam) {
|
|
466
|
+
const config = isUpdateRequest ? 'null,{headers}' : '{headers}';
|
|
467
|
+
output += `
|
|
468
|
+
type ${componentName}Params = {
|
|
469
|
+
${headerParam}
|
|
470
|
+
${paramsTypes}
|
|
471
|
+
};
|
|
472
|
+
|
|
473
|
+
const ${fetchName} = async (props: ${componentName}Params) => {
|
|
474
|
+
const headers = {${generateProps(header)}}
|
|
475
|
+
const result = await api.${verb}<${responseTypes}>(\`${route.replace(/\{/g, '{props.')}\`, ${config})
|
|
476
|
+
return result.data
|
|
477
|
+
}
|
|
478
|
+
`;
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
if (!requestBodyComponent && paramsInPath.length && queryParam && headerParam) {
|
|
482
|
+
output += `// TODO: NOT SUPPORTED (paramsInPath && queryParam && headerParam)`;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
if (requestBodyComponent && paramsInPath.length && !queryParam && headerParam) {
|
|
486
|
+
output += `// TODO: NOT SUPPORTED (requestBodyComponent && paramsInPath && headerParam)`;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
return { implementation: output, imports, queryImports };
|
|
490
|
+
};
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
export const generateImports = ({
|
|
2
|
+
schemaName,
|
|
3
|
+
apiDirectory,
|
|
4
|
+
queryClientDir,
|
|
5
|
+
schemaImports,
|
|
6
|
+
queryImports,
|
|
7
|
+
}: {
|
|
8
|
+
apiDirectory: string;
|
|
9
|
+
queryClientDir: string;
|
|
10
|
+
schemaName: string;
|
|
11
|
+
schemaImports: string[];
|
|
12
|
+
queryImports: ('query' | 'mutation' | 'infiniteQuery')[];
|
|
13
|
+
}) => {
|
|
14
|
+
const importTypes = schemaImports.join(',');
|
|
15
|
+
let imports = [] as string[];
|
|
16
|
+
if (queryImports.includes('query')) {
|
|
17
|
+
imports = [...imports, 'useQuery', 'UseQueryOptions', 'QueryKey', 'SetDataOptions', 'QueryFilters'];
|
|
18
|
+
}
|
|
19
|
+
if (queryImports.includes('infiniteQuery')) {
|
|
20
|
+
imports = [...imports, 'useInfiniteQuery', 'UseInfiniteQueryOptions', 'QueryKey'];
|
|
21
|
+
}
|
|
22
|
+
if (queryImports.includes('mutation')) {
|
|
23
|
+
imports = [...imports, 'UseMutationOptions', 'useMutation'];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const importString = [...new Set(imports)].join(',');
|
|
27
|
+
|
|
28
|
+
return `
|
|
29
|
+
import {
|
|
30
|
+
${importString}
|
|
31
|
+
} from '@tanstack/react-query';
|
|
32
|
+
|
|
33
|
+
import { AxiosError } from 'axios';
|
|
34
|
+
import { api } from '${apiDirectory}';
|
|
35
|
+
import { queryClient } from '${queryClientDir}';
|
|
36
|
+
|
|
37
|
+
import {${importTypes}} from './${schemaName}'
|
|
38
|
+
|
|
39
|
+
type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput);
|
|
40
|
+
`;
|
|
41
|
+
};
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import pasCase from 'case';
|
|
2
|
+
import lodash from 'lodash';
|
|
3
|
+
const { isEmpty } = lodash;
|
|
4
|
+
const { pascal } = pasCase;
|
|
5
|
+
import { ComponentsObject, OpenAPIObject, SchemaObject } from 'openapi3-ts';
|
|
6
|
+
import { formatDescription, getScalar, isReference, resolveValue } from './utils.js';
|
|
7
|
+
|
|
8
|
+
import { getDocs, getResReqTypes } from './utils.js';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Generate the interface string
|
|
12
|
+
*/
|
|
13
|
+
const generateInterface = (name: string, schema: SchemaObject) => {
|
|
14
|
+
const scalar = getScalar(schema);
|
|
15
|
+
return `${formatDescription(schema.description)}
|
|
16
|
+
export type ${pascal(name)} = ${scalar}
|
|
17
|
+
`;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Extract all types from #/components/schemas
|
|
22
|
+
*/
|
|
23
|
+
const generateSchemasDefinition = (schemas: ComponentsObject['schemas'] = {}) => {
|
|
24
|
+
if (isEmpty(schemas)) {
|
|
25
|
+
return '';
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
return (
|
|
29
|
+
'\n // SCEHMAS \n' +
|
|
30
|
+
Object.entries(schemas)
|
|
31
|
+
.map(([name, schema]) =>
|
|
32
|
+
!isReference(schema) &&
|
|
33
|
+
(!schema.type || schema.type === 'object') &&
|
|
34
|
+
!schema.allOf &&
|
|
35
|
+
!schema.oneOf &&
|
|
36
|
+
!isReference(schema) &&
|
|
37
|
+
!schema.nullable
|
|
38
|
+
? generateInterface(name, schema)
|
|
39
|
+
: `${formatDescription(isReference(schema) ? undefined : schema.description)} export type ${pascal(
|
|
40
|
+
name
|
|
41
|
+
)} = ${resolveValue(schema)};`
|
|
42
|
+
)
|
|
43
|
+
.join('\n\n') +
|
|
44
|
+
'\n'
|
|
45
|
+
);
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Extract all types from #/components/requestBodies
|
|
50
|
+
*/
|
|
51
|
+
const generateRequestBodiesDefinition = (requestBodies: ComponentsObject['requestBodies'] = {}) => {
|
|
52
|
+
if (isEmpty(requestBodies)) {
|
|
53
|
+
return '';
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return (
|
|
57
|
+
'\n // REQUEST BODIES \n' +
|
|
58
|
+
Object.entries(requestBodies)
|
|
59
|
+
.map(([name, requestBody]) => {
|
|
60
|
+
const doc = getDocs(requestBody);
|
|
61
|
+
const type = getResReqTypes([['', requestBody]]);
|
|
62
|
+
const isEmptyInterface = type === '{}';
|
|
63
|
+
if (isEmptyInterface) {
|
|
64
|
+
return `${doc}\nexport type ${pascal(name)}RequestBody = ${type}`;
|
|
65
|
+
} else if (type.includes('{') && !type.includes('|') && !type.includes('&')) {
|
|
66
|
+
return `${doc}\nexport type ${pascal(name)}RequestBody = ${type}`;
|
|
67
|
+
} else {
|
|
68
|
+
return `${doc}\nexport type ${pascal(name)}RequestBody = ${type};`;
|
|
69
|
+
}
|
|
70
|
+
})
|
|
71
|
+
.join('\n\n') +
|
|
72
|
+
'\n'
|
|
73
|
+
);
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Extract all types from #/components/responses
|
|
78
|
+
*/
|
|
79
|
+
const generateResponsesDefinition = (responses: ComponentsObject['responses'] = {}) => {
|
|
80
|
+
if (isEmpty(responses)) {
|
|
81
|
+
return '';
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
return (
|
|
85
|
+
'\n // RESPONSES \n' +
|
|
86
|
+
Object.entries(responses)
|
|
87
|
+
.map(([name, response]) => {
|
|
88
|
+
const doc = getDocs(response);
|
|
89
|
+
const type = getResReqTypes([['', response]]);
|
|
90
|
+
const isEmptyInterface = type === '{}';
|
|
91
|
+
if (isEmptyInterface) {
|
|
92
|
+
return `export type RQ${pascal(name)}Response = ${type}`;
|
|
93
|
+
} else if (type.includes('{') && !type.includes('|') && !type.includes('&')) {
|
|
94
|
+
return `${doc}export type RQ${pascal(name)}Response = ${type}`;
|
|
95
|
+
} else {
|
|
96
|
+
return `${doc}export type RQ${pascal(name)}Response = ${type};`;
|
|
97
|
+
}
|
|
98
|
+
})
|
|
99
|
+
.join('\n\n') +
|
|
100
|
+
'\n'
|
|
101
|
+
);
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Extract all types from #/components/schemas
|
|
106
|
+
*/
|
|
107
|
+
export const generateSchemas = ({ spec }: { spec: OpenAPIObject }) => {
|
|
108
|
+
const schemaOutput =
|
|
109
|
+
generateRequestBodiesDefinition(spec.components?.requestBodies) +
|
|
110
|
+
generateResponsesDefinition(spec.components?.responses) +
|
|
111
|
+
generateSchemasDefinition(spec.components?.schemas);
|
|
112
|
+
|
|
113
|
+
return schemaOutput;
|
|
114
|
+
};
|