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