react-query-lightbase-codegen 0.0.5 → 0.0.8
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.
|
@@ -4,20 +4,18 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.importOpenApi = exports.generateRestfulComponent = exports.formatDescription = exports.generateResponsesDefinition = exports.generateRequestBodiesDefinition = exports.generateSchemasDefinition = exports.resolveDiscriminator = exports.generateInterface = exports.getParamsInPath = exports.getResReqTypes = exports.resolveValue = exports.getObject = exports.getArray = exports.getRef = exports.getScalar = exports.isReference = void 0;
|
|
7
|
-
const case_1 = require("case");
|
|
8
|
-
const
|
|
9
|
-
const
|
|
10
|
-
const
|
|
11
|
-
const set_1 = __importDefault(require("lodash/set"));
|
|
12
|
-
const uniq_1 = __importDefault(require("lodash/uniq"));
|
|
7
|
+
const case_1 = __importDefault(require("case"));
|
|
8
|
+
const lodash_1 = __importDefault(require("lodash"));
|
|
9
|
+
const { pascal } = case_1.default;
|
|
10
|
+
const { uniq, get, groupBy, isEmpty, set } = lodash_1.default;
|
|
13
11
|
const swagger2openapi_1 = __importDefault(require("swagger2openapi"));
|
|
14
|
-
const
|
|
12
|
+
const js_yaml_1 = __importDefault(require("js-yaml"));
|
|
15
13
|
const IdentifierRegexp = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
|
|
16
14
|
/**
|
|
17
15
|
* Import and parse the openapi spec from a yaml/json
|
|
18
16
|
*/
|
|
19
17
|
const importSpecs = (data, extension) => {
|
|
20
|
-
const schema = extension === 'yaml' ?
|
|
18
|
+
const schema = extension === 'yaml' ? js_yaml_1.default.load(data) : JSON.parse(data);
|
|
21
19
|
return new Promise((resolve, reject) => {
|
|
22
20
|
if (!schema.openapi || !schema.openapi.startsWith('3.')) {
|
|
23
21
|
swagger2openapi_1.default.convertObj(schema, {}, (err, convertedObj) => {
|
|
@@ -53,12 +51,12 @@ const getScalar = (item) => {
|
|
|
53
51
|
case 'boolean':
|
|
54
52
|
return 'boolean' + nullable;
|
|
55
53
|
case 'array':
|
|
56
|
-
return exports.getArray(item) + nullable;
|
|
54
|
+
return (0, exports.getArray)(item) + nullable;
|
|
57
55
|
case 'string':
|
|
58
56
|
return (item.enum ? `"${item.enum.join(`" | "`)}"` : 'string') + nullable;
|
|
59
57
|
case 'object':
|
|
60
58
|
default:
|
|
61
|
-
return exports.getObject(item) + nullable;
|
|
59
|
+
return (0, exports.getObject)(item) + nullable;
|
|
62
60
|
}
|
|
63
61
|
};
|
|
64
62
|
exports.getScalar = getScalar;
|
|
@@ -67,16 +65,16 @@ exports.getScalar = getScalar;
|
|
|
67
65
|
*/
|
|
68
66
|
const getRef = ($ref) => {
|
|
69
67
|
if ($ref.startsWith('#/components/schemas')) {
|
|
70
|
-
return
|
|
68
|
+
return pascal($ref.replace('#/components/schemas/', ''));
|
|
71
69
|
}
|
|
72
70
|
else if ($ref.startsWith('#/components/responses')) {
|
|
73
|
-
return
|
|
71
|
+
return pascal($ref.replace('#/components/responses/', '')) + 'Response';
|
|
74
72
|
}
|
|
75
73
|
else if ($ref.startsWith('#/components/parameters')) {
|
|
76
|
-
return
|
|
74
|
+
return pascal($ref.replace('#/components/parameters/', '')) + 'Parameter';
|
|
77
75
|
}
|
|
78
76
|
else if ($ref.startsWith('#/components/requestBodies')) {
|
|
79
|
-
return
|
|
77
|
+
return pascal($ref.replace('#/components/requestBodies/', '')) + 'RequestBody';
|
|
80
78
|
}
|
|
81
79
|
else {
|
|
82
80
|
throw new Error('This library only resolve $ref that are include into `#/components/*` for now');
|
|
@@ -88,11 +86,11 @@ exports.getRef = getRef;
|
|
|
88
86
|
*/
|
|
89
87
|
const getArray = (item) => {
|
|
90
88
|
if (item.items) {
|
|
91
|
-
if (!exports.isReference(item.items) && (item.items.oneOf || item.items.allOf || item.items.enum)) {
|
|
92
|
-
return `(${exports.resolveValue(item.items)})[]`;
|
|
89
|
+
if (!(0, exports.isReference)(item.items) && (item.items.oneOf || item.items.allOf || item.items.enum)) {
|
|
90
|
+
return `(${(0, exports.resolveValue)(item.items)})[]`;
|
|
93
91
|
}
|
|
94
92
|
else {
|
|
95
|
-
return `${exports.resolveValue(item.items)}[]`;
|
|
93
|
+
return `${(0, exports.resolveValue)(item.items)}[]`;
|
|
96
94
|
}
|
|
97
95
|
}
|
|
98
96
|
else {
|
|
@@ -104,8 +102,8 @@ exports.getArray = getArray;
|
|
|
104
102
|
* Return the output type from an object
|
|
105
103
|
*/
|
|
106
104
|
const getObject = (item) => {
|
|
107
|
-
if (exports.isReference(item)) {
|
|
108
|
-
return exports.getRef(item.$ref);
|
|
105
|
+
if ((0, exports.isReference)(item)) {
|
|
106
|
+
return (0, exports.getRef)(item.$ref);
|
|
109
107
|
}
|
|
110
108
|
if (item.allOf) {
|
|
111
109
|
return item.allOf.map(exports.resolveValue).join(' & ');
|
|
@@ -119,7 +117,7 @@ const getObject = (item) => {
|
|
|
119
117
|
// Free form object (https://swagger.io/docs/specification/data-models/data-types/#free-form)
|
|
120
118
|
if (item.type === 'object' &&
|
|
121
119
|
!item.properties &&
|
|
122
|
-
(!item.additionalProperties || item.additionalProperties === true ||
|
|
120
|
+
(!item.additionalProperties || item.additionalProperties === true || isEmpty(item.additionalProperties))) {
|
|
123
121
|
return '{[key: string]: any}';
|
|
124
122
|
}
|
|
125
123
|
// Consolidation of item.properties & item.additionalProperties
|
|
@@ -127,10 +125,10 @@ const getObject = (item) => {
|
|
|
127
125
|
if (item.properties) {
|
|
128
126
|
output += Object.entries(item.properties)
|
|
129
127
|
.map(([key, prop]) => {
|
|
130
|
-
const doc = exports.isReference(prop) ? '' : exports.formatDescription(prop.description, 2);
|
|
128
|
+
const doc = (0, exports.isReference)(prop) ? '' : (0, exports.formatDescription)(prop.description, 2);
|
|
131
129
|
const isRequired = (item.required || []).includes(key);
|
|
132
130
|
const processedKey = IdentifierRegexp.test(key) ? key : `"${key}"`;
|
|
133
|
-
return ` ${doc}${processedKey}${isRequired ? '' : '?'}: ${exports.resolveValue(prop)};`;
|
|
131
|
+
return ` ${doc}${processedKey}${isRequired ? '' : '?'}: ${(0, exports.resolveValue)(prop)};`;
|
|
134
132
|
})
|
|
135
133
|
.join('\n');
|
|
136
134
|
}
|
|
@@ -138,7 +136,7 @@ const getObject = (item) => {
|
|
|
138
136
|
if (item.properties) {
|
|
139
137
|
output += '\n';
|
|
140
138
|
}
|
|
141
|
-
output += ` [key: string]: ${item.additionalProperties === true ? 'any' : exports.resolveValue(item.additionalProperties)};`;
|
|
139
|
+
output += ` [key: string]: ${item.additionalProperties === true ? 'any' : (0, exports.resolveValue)(item.additionalProperties)};`;
|
|
142
140
|
}
|
|
143
141
|
if (item.properties || item.additionalProperties) {
|
|
144
142
|
if (output === '{\n') {
|
|
@@ -152,24 +150,24 @@ exports.getObject = getObject;
|
|
|
152
150
|
/**
|
|
153
151
|
* Resolve the value of a schema object to a proper type definition.
|
|
154
152
|
*/
|
|
155
|
-
const resolveValue = (schema) => exports.isReference(schema) ? exports.getRef(schema.$ref) : exports.getScalar(schema);
|
|
153
|
+
const resolveValue = (schema) => (0, exports.isReference)(schema) ? (0, exports.getRef)(schema.$ref) : (0, exports.getScalar)(schema);
|
|
156
154
|
exports.resolveValue = resolveValue;
|
|
157
155
|
/**
|
|
158
156
|
* Extract responses / request types from open-api specs
|
|
159
157
|
*/
|
|
160
|
-
const getResReqTypes = (responsesOrRequests) =>
|
|
158
|
+
const getResReqTypes = (responsesOrRequests) => uniq(responsesOrRequests.map(([_, res]) => {
|
|
161
159
|
if (!res) {
|
|
162
160
|
return 'void';
|
|
163
161
|
}
|
|
164
|
-
if (exports.isReference(res)) {
|
|
165
|
-
return exports.getRef(res.$ref);
|
|
162
|
+
if ((0, exports.isReference)(res)) {
|
|
163
|
+
return (0, exports.getRef)(res.$ref);
|
|
166
164
|
}
|
|
167
165
|
if (res.content) {
|
|
168
166
|
for (let contentType of Object.keys(res.content)) {
|
|
169
167
|
if (contentType.startsWith('application/json') ||
|
|
170
168
|
contentType.startsWith('application/octet-stream')) {
|
|
171
169
|
const schema = res.content[contentType].schema;
|
|
172
|
-
return exports.resolveValue(schema);
|
|
170
|
+
return (0, exports.resolveValue)(schema);
|
|
173
171
|
}
|
|
174
172
|
}
|
|
175
173
|
return 'void';
|
|
@@ -200,8 +198,8 @@ exports.getParamsInPath = getParamsInPath;
|
|
|
200
198
|
* Generate the interface string
|
|
201
199
|
*/
|
|
202
200
|
const generateInterface = (name, schema) => {
|
|
203
|
-
const scalar = exports.getScalar(schema);
|
|
204
|
-
return `${exports.formatDescription(schema.description)}export interface ${
|
|
201
|
+
const scalar = (0, exports.getScalar)(schema);
|
|
202
|
+
return `${(0, exports.formatDescription)(schema.description)}export interface ${pascal(name)} ${scalar}`;
|
|
205
203
|
};
|
|
206
204
|
exports.generateInterface = generateInterface;
|
|
207
205
|
/**
|
|
@@ -212,7 +210,7 @@ exports.generateInterface = generateInterface;
|
|
|
212
210
|
const resolveDiscriminator = (specs) => {
|
|
213
211
|
if (specs.components && specs.components.schemas) {
|
|
214
212
|
Object.values(specs.components.schemas).forEach((schema) => {
|
|
215
|
-
if (exports.isReference(schema) || !schema.discriminator || !schema.discriminator.mapping) {
|
|
213
|
+
if ((0, exports.isReference)(schema) || !schema.discriminator || !schema.discriminator.mapping) {
|
|
216
214
|
return;
|
|
217
215
|
}
|
|
218
216
|
const { mapping, propertyName } = schema.discriminator;
|
|
@@ -220,7 +218,7 @@ const resolveDiscriminator = (specs) => {
|
|
|
220
218
|
if (!ref.startsWith('#/components/schemas/')) {
|
|
221
219
|
throw new Error('Discriminator mapping outside of `#/components/schemas` is not supported');
|
|
222
220
|
}
|
|
223
|
-
|
|
221
|
+
set(specs, `components.schemas.${ref.slice('#/components/schemas/'.length)}.properties.${propertyName}.enum`, [name]);
|
|
224
222
|
});
|
|
225
223
|
});
|
|
226
224
|
}
|
|
@@ -230,18 +228,18 @@ exports.resolveDiscriminator = resolveDiscriminator;
|
|
|
230
228
|
* Extract all types from #/components/schemas
|
|
231
229
|
*/
|
|
232
230
|
const generateSchemasDefinition = (schemas = {}) => {
|
|
233
|
-
if (
|
|
231
|
+
if (isEmpty(schemas)) {
|
|
234
232
|
return '';
|
|
235
233
|
}
|
|
236
234
|
return (Object.entries(schemas)
|
|
237
|
-
.map(([name, schema]) => !exports.isReference(schema) &&
|
|
235
|
+
.map(([name, schema]) => !(0, exports.isReference)(schema) &&
|
|
238
236
|
(!schema.type || schema.type === 'object') &&
|
|
239
237
|
!schema.allOf &&
|
|
240
238
|
!schema.oneOf &&
|
|
241
|
-
!exports.isReference(schema) &&
|
|
239
|
+
!(0, exports.isReference)(schema) &&
|
|
242
240
|
!schema.nullable
|
|
243
|
-
? exports.generateInterface(name, schema)
|
|
244
|
-
: `${exports.formatDescription(exports.isReference(schema) ? undefined : schema.description)}export type ${
|
|
241
|
+
? (0, exports.generateInterface)(name, schema)
|
|
242
|
+
: `${(0, exports.formatDescription)((0, exports.isReference)(schema) ? undefined : schema.description)}export type ${pascal(name)} = ${(0, exports.resolveValue)(schema)};`)
|
|
245
243
|
.join('\n\n') + '\n');
|
|
246
244
|
};
|
|
247
245
|
exports.generateSchemasDefinition = generateSchemasDefinition;
|
|
@@ -249,23 +247,23 @@ exports.generateSchemasDefinition = generateSchemasDefinition;
|
|
|
249
247
|
* Extract all types from #/components/requestBodies
|
|
250
248
|
*/
|
|
251
249
|
const generateRequestBodiesDefinition = (requestBodies = {}) => {
|
|
252
|
-
if (
|
|
250
|
+
if (isEmpty(requestBodies)) {
|
|
253
251
|
return '';
|
|
254
252
|
}
|
|
255
253
|
return ('\n' +
|
|
256
254
|
Object.entries(requestBodies)
|
|
257
255
|
.map(([name, requestBody]) => {
|
|
258
|
-
const doc = exports.isReference(requestBody) ? '' : exports.formatDescription(requestBody.description);
|
|
259
|
-
const type = exports.getResReqTypes([['', requestBody]]);
|
|
256
|
+
const doc = (0, exports.isReference)(requestBody) ? '' : (0, exports.formatDescription)(requestBody.description);
|
|
257
|
+
const type = (0, exports.getResReqTypes)([['', requestBody]]);
|
|
260
258
|
const isEmptyInterface = type === '{}';
|
|
261
259
|
if (isEmptyInterface) {
|
|
262
|
-
return `export interface ${
|
|
260
|
+
return `export interface ${pascal(name)}RequestBody ${type}`;
|
|
263
261
|
}
|
|
264
262
|
else if (type.includes('{') && !type.includes('|') && !type.includes('&')) {
|
|
265
|
-
return `${doc}export interface ${
|
|
263
|
+
return `${doc}export interface ${pascal(name)}RequestBody ${type}`;
|
|
266
264
|
}
|
|
267
265
|
else {
|
|
268
|
-
return `${doc}export type ${
|
|
266
|
+
return `${doc}export type ${pascal(name)}RequestBody = ${type};`;
|
|
269
267
|
}
|
|
270
268
|
})
|
|
271
269
|
.join('\n\n') +
|
|
@@ -276,23 +274,23 @@ exports.generateRequestBodiesDefinition = generateRequestBodiesDefinition;
|
|
|
276
274
|
* Extract all types from #/components/responses
|
|
277
275
|
*/
|
|
278
276
|
const generateResponsesDefinition = (responses = {}) => {
|
|
279
|
-
if (
|
|
277
|
+
if (isEmpty(responses)) {
|
|
280
278
|
return '';
|
|
281
279
|
}
|
|
282
280
|
return ('\n' +
|
|
283
281
|
Object.entries(responses)
|
|
284
282
|
.map(([name, response]) => {
|
|
285
|
-
const doc = exports.isReference(response) ? '' : exports.formatDescription(response.description);
|
|
286
|
-
const type = exports.getResReqTypes([['', response]]);
|
|
283
|
+
const doc = (0, exports.isReference)(response) ? '' : (0, exports.formatDescription)(response.description);
|
|
284
|
+
const type = (0, exports.getResReqTypes)([['', response]]);
|
|
287
285
|
const isEmptyInterface = type === '{}';
|
|
288
286
|
if (isEmptyInterface) {
|
|
289
|
-
return `export interface RQ${
|
|
287
|
+
return `export interface RQ${pascal(name)}Response ${type}`;
|
|
290
288
|
}
|
|
291
289
|
else if (type.includes('{') && !type.includes('|') && !type.includes('&')) {
|
|
292
|
-
return `${doc}export interface RQ${
|
|
290
|
+
return `${doc}export interface RQ${pascal(name)}Response ${type}`;
|
|
293
291
|
}
|
|
294
292
|
else {
|
|
295
|
-
return `${doc}export type RQ${
|
|
293
|
+
return `${doc}export type RQ${pascal(name)}Response = ${type};`;
|
|
296
294
|
}
|
|
297
295
|
})
|
|
298
296
|
.join('\n\n') +
|
|
@@ -324,15 +322,15 @@ const generateRestfulComponent = (operation, verb, route, operationIds, paramete
|
|
|
324
322
|
route = route.replace(/\{/g, '${'); // `/pet/{id}` => `/pet/${id}`
|
|
325
323
|
// Remove the last param of the route if we are in the DELETE case
|
|
326
324
|
let lastParamInTheRoute = null;
|
|
327
|
-
const componentName =
|
|
325
|
+
const componentName = pascal(operationId);
|
|
328
326
|
const isOk = ([statusCode]) => statusCode.toString().startsWith('2');
|
|
329
|
-
const responseTypes = exports.getResReqTypes(Object.entries(operation.responses).filter(isOk)) || 'void';
|
|
330
|
-
const requestBodyTypes = exports.getResReqTypes([['body', operation.requestBody]]);
|
|
327
|
+
const responseTypes = (0, exports.getResReqTypes)(Object.entries(operation.responses).filter(isOk)) || 'void';
|
|
328
|
+
const requestBodyTypes = (0, exports.getResReqTypes)([['body', operation.requestBody]]);
|
|
331
329
|
const needAResponseComponent = true;
|
|
332
|
-
const paramsInPath = exports.getParamsInPath(route).filter((param) => !(verb === 'delete' && param === lastParamInTheRoute));
|
|
333
|
-
const { query: queryParams = [], path: pathParams = [] } =
|
|
334
|
-
if (exports.isReference(p)) {
|
|
335
|
-
return
|
|
330
|
+
const paramsInPath = (0, exports.getParamsInPath)(route).filter((param) => !(verb === 'delete' && param === lastParamInTheRoute));
|
|
331
|
+
const { query: queryParams = [], path: pathParams = [], header: headerParams = [] } = groupBy([...parameters, ...(operation.parameters || [])].map((p) => {
|
|
332
|
+
if ((0, exports.isReference)(p)) {
|
|
333
|
+
return get(schemasComponents, p.$ref.replace('#/components/', '').replace('/', '.'));
|
|
336
334
|
}
|
|
337
335
|
else {
|
|
338
336
|
return p;
|
|
@@ -342,7 +340,7 @@ const generateRestfulComponent = (operation, verb, route, operationIds, paramete
|
|
|
342
340
|
.map((p) => {
|
|
343
341
|
try {
|
|
344
342
|
const { name, required, schema } = pathParams.find((i) => i.name === p);
|
|
345
|
-
return `${name}${required ? '' : '?'}: ${exports.resolveValue(schema)}`;
|
|
343
|
+
return `${name}${required ? '' : '?'}: ${(0, exports.resolveValue)(schema)}`;
|
|
346
344
|
}
|
|
347
345
|
catch (err) {
|
|
348
346
|
throw new Error(`The path params ${p} can't be found in parameters (${operationId})`);
|
|
@@ -352,13 +350,24 @@ const generateRestfulComponent = (operation, verb, route, operationIds, paramete
|
|
|
352
350
|
const queryParamsType = queryParams
|
|
353
351
|
.map((p) => {
|
|
354
352
|
const processedName = IdentifierRegexp.test(p.name) ? p.name : `"${p.name}"`;
|
|
355
|
-
return `${exports.formatDescription(p.description, 2)}${processedName}${p.required ? '' : '?'}: ${exports.resolveValue(p.schema)}`;
|
|
353
|
+
return `${(0, exports.formatDescription)(p.description, 2)}${processedName}${p.required ? '' : '?'}: ${(0, exports.resolveValue)(p.schema)}`;
|
|
356
354
|
})
|
|
357
355
|
.join(';\n ');
|
|
356
|
+
const headerType = headerParams
|
|
357
|
+
.map((p) => {
|
|
358
|
+
try {
|
|
359
|
+
const { name, required, schema } = headerParams.find((i) => i.name === p.name);
|
|
360
|
+
return `"${name}"${required ? '' : '?'}: ${(0, exports.resolveValue)(schema)}`;
|
|
361
|
+
}
|
|
362
|
+
catch (err) {
|
|
363
|
+
throw new Error(`The path params ${p} can't be found in parameters (${operationId})`);
|
|
364
|
+
}
|
|
365
|
+
})
|
|
366
|
+
.join('; ');
|
|
358
367
|
// Retrieve the type of the param for delete verb
|
|
359
368
|
const lastParamInTheRouteDefinition = operation.parameters && lastParamInTheRoute
|
|
360
369
|
? operation.parameters.find((p) => {
|
|
361
|
-
if (exports.isReference(p)) {
|
|
370
|
+
if ((0, exports.isReference)(p)) {
|
|
362
371
|
return false;
|
|
363
372
|
}
|
|
364
373
|
return p.name === lastParamInTheRoute;
|
|
@@ -371,7 +380,7 @@ const generateRestfulComponent = (operation, verb, route, operationIds, paramete
|
|
|
371
380
|
if (verb !== 'get') {
|
|
372
381
|
genericsTypes = `${needAResponseComponent ? componentName + 'Res' : responseTypes}`;
|
|
373
382
|
}
|
|
374
|
-
const description = exports.formatDescription(operation.summary && operation.description
|
|
383
|
+
const description = (0, exports.formatDescription)(operation.summary && operation.description
|
|
375
384
|
? `${operation.summary}\n\n${operation.description}`
|
|
376
385
|
: `${operation.summary || ''}${operation.description || ''}`);
|
|
377
386
|
let output = `\n\n${description}`;
|
|
@@ -379,10 +388,12 @@ const generateRestfulComponent = (operation, verb, route, operationIds, paramete
|
|
|
379
388
|
output += `
|
|
380
389
|
${needAResponseComponent ? `export ${typeOrInterface} ${responseTypes}` : ''}
|
|
381
390
|
`;
|
|
391
|
+
const headerParam = headerType && headerType !== 'void' ? `${headerType};` : '';
|
|
382
392
|
const queryParam = queryParamsType && queryParamsType !== 'void' ? `${queryParamsType}` : '';
|
|
383
393
|
const requestBodyComponent = requestBodyTypes && requestBodyTypes !== 'void' ? `${requestBodyTypes}` : '';
|
|
394
|
+
console.log(headerParam);
|
|
384
395
|
// QUERIES
|
|
385
|
-
if (!requestBodyComponent && paramsInPath.length && !queryParam) {
|
|
396
|
+
if (!requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
|
|
386
397
|
output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
|
|
387
398
|
${paramsTypes};
|
|
388
399
|
options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
|
|
@@ -416,7 +427,7 @@ const generateRestfulComponent = (operation, verb, route, operationIds, paramete
|
|
|
416
427
|
props?.options
|
|
417
428
|
)};`;
|
|
418
429
|
}
|
|
419
|
-
if (!requestBodyComponent && paramsInPath.length && queryParam) {
|
|
430
|
+
if (!requestBodyComponent && paramsInPath.length && queryParam && !headerParam) {
|
|
420
431
|
output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
|
|
421
432
|
${paramsTypes};
|
|
422
433
|
${queryParamsType};
|
|
@@ -455,7 +466,7 @@ const generateRestfulComponent = (operation, verb, route, operationIds, paramete
|
|
|
455
466
|
props?.options
|
|
456
467
|
)};`;
|
|
457
468
|
}
|
|
458
|
-
if (!requestBodyComponent && !paramsInPath.length && !queryParam) {
|
|
469
|
+
if (!requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
|
|
459
470
|
output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
|
|
460
471
|
options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
|
|
461
472
|
}
|
|
@@ -484,7 +495,7 @@ const generateRestfulComponent = (operation, verb, route, operationIds, paramete
|
|
|
484
495
|
props?.options
|
|
485
496
|
)};`;
|
|
486
497
|
}
|
|
487
|
-
if (!requestBodyComponent && !paramsInPath.length && queryParam) {
|
|
498
|
+
if (!requestBodyComponent && !paramsInPath.length && queryParam && !headerParam) {
|
|
488
499
|
output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
|
|
489
500
|
${queryParamsType};
|
|
490
501
|
options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
|
|
@@ -525,7 +536,7 @@ const generateRestfulComponent = (operation, verb, route, operationIds, paramete
|
|
|
525
536
|
props?.options
|
|
526
537
|
)};`;
|
|
527
538
|
}
|
|
528
|
-
if (requestBodyComponent && !paramsInPath.length && !queryParam) {
|
|
539
|
+
if (requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
|
|
529
540
|
output += `type ${componentName}QueryVariables = ${requestBodyComponent};
|
|
530
541
|
interface ${componentName}QueryProps<T = ${genericsTypes}> extends ${componentName}QueryVariables {
|
|
531
542
|
options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
|
|
@@ -556,7 +567,7 @@ const generateRestfulComponent = (operation, verb, route, operationIds, paramete
|
|
|
556
567
|
props?.options
|
|
557
568
|
)};`;
|
|
558
569
|
}
|
|
559
|
-
if (requestBodyComponent && paramsInPath.length && !queryParam) {
|
|
570
|
+
if (requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
|
|
560
571
|
output += `interface ${componentName}QueryProps<T = ${genericsTypes}> extends ${requestBodyComponent
|
|
561
572
|
.replace('{', '')
|
|
562
573
|
.replace('}', '')} {
|
|
@@ -567,7 +578,6 @@ const generateRestfulComponent = (operation, verb, route, operationIds, paramete
|
|
|
567
578
|
return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props), { enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
|
|
568
579
|
);}
|
|
569
580
|
|
|
570
|
-
// HEHEH
|
|
571
581
|
use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'>) => {
|
|
572
582
|
const {${paramsInPath.join(', ')}, ...body} = props
|
|
573
583
|
const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
|
|
@@ -578,7 +588,6 @@ const generateRestfulComponent = (operation, verb, route, operationIds, paramete
|
|
|
578
588
|
|
|
579
589
|
use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
|
|
580
590
|
|
|
581
|
-
|
|
582
591
|
`;
|
|
583
592
|
output += `type ${componentName}MutationVariables = {${paramsTypes}} & ${requestBodyComponent}
|
|
584
593
|
interface ${componentName}MutationProps<T> {
|
|
@@ -589,36 +598,152 @@ const generateRestfulComponent = (operation, verb, route, operationIds, paramete
|
|
|
589
598
|
props?.options
|
|
590
599
|
)};`;
|
|
591
600
|
}
|
|
592
|
-
if (requestBodyComponent && queryParam) {
|
|
601
|
+
if (requestBodyComponent && queryParam && !headerParam) {
|
|
602
|
+
output += `// TODO: CODEGEN DOES NOT SUPPORT QUERYPARAM AND REQUESTBODY`;
|
|
603
|
+
}
|
|
604
|
+
if (requestBodyComponent && queryParam && headerParam) {
|
|
593
605
|
output += `// TODO: CODEGEN DOES NOT SUPPORT QUERYPARAM AND REQUESTBODY`;
|
|
594
606
|
}
|
|
607
|
+
if (!requestBodyComponent && paramsInPath.length && !queryParam && headerParam) {
|
|
608
|
+
output += `// TODO: CODEGEN DOES NOT SUPPORT paramsInPath AND headerParam`;
|
|
609
|
+
}
|
|
610
|
+
if (!requestBodyComponent && paramsInPath.length && queryParam && headerParam) {
|
|
611
|
+
output += `// TODO: CODEGEN DOES NOT SUPPORT paramsInPath AND headerParam AND headerParam`;
|
|
612
|
+
}
|
|
613
|
+
if (!requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
|
|
614
|
+
output += `
|
|
615
|
+
// HELLO
|
|
616
|
+
type ${componentName}HeaderVariables = {${headerParam}};
|
|
617
|
+
type ${componentName}QueryProps<T = ${genericsTypes}> = ${componentName}HeaderVariables & {
|
|
618
|
+
options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
|
|
619
|
+
}
|
|
620
|
+
export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
|
|
621
|
+
return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
|
|
622
|
+
{ enabled: !!props${headerParams.map((param) => `["${param.name}"]`).join(' && !!props')}, ...options }
|
|
623
|
+
);}
|
|
624
|
+
|
|
625
|
+
use${componentName}Query.fetch = async (headers: ${componentName}HeaderVariables) => {
|
|
626
|
+
const result = await api.${verb}<${genericsTypes}>(\`${route}\`, {headers: headers});
|
|
627
|
+
return result.data;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
|
|
631
|
+
|
|
632
|
+
use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
|
|
633
|
+
|
|
634
|
+
type ${componentName}MutationProps<T> = {
|
|
635
|
+
options?: UseMutationOptions<${genericsTypes}, AxiosError, void, T>
|
|
636
|
+
}
|
|
637
|
+
export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
|
|
638
|
+
return useMutation(async () => {
|
|
639
|
+
const result = await api.${verb}<${genericsTypes}>(\`${route}\`);
|
|
640
|
+
return result.data;
|
|
641
|
+
},
|
|
642
|
+
props?.options
|
|
643
|
+
)};`;
|
|
644
|
+
}
|
|
645
|
+
if (!requestBodyComponent && !paramsInPath.length && queryParam && headerParam) {
|
|
646
|
+
output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
|
|
647
|
+
${queryParamsType};
|
|
648
|
+
options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
|
|
649
|
+
}
|
|
650
|
+
export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
|
|
651
|
+
return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
|
|
652
|
+
{ enabled: !!props.${queryParams.map((param) => param.name).join(' && !!props.')}, ...options }
|
|
653
|
+
);}
|
|
654
|
+
|
|
655
|
+
use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'>) => {
|
|
656
|
+
const params = queryString.stringify({${queryParams
|
|
657
|
+
.map((param) => `${param.name}: props.${param.name}`)
|
|
658
|
+
.join(',')}});
|
|
659
|
+
const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
|
|
660
|
+
return result.data;
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
|
|
664
|
+
|
|
665
|
+
use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
|
|
666
|
+
|
|
667
|
+
interface ${componentName}MutationVariables {
|
|
668
|
+
${queryParamsType}
|
|
669
|
+
}
|
|
670
|
+
interface ${componentName}MutationProps<T> {
|
|
671
|
+
options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
|
|
675
|
+
return useMutation(async (data) => {
|
|
676
|
+
const params = queryString.stringify({${queryParams
|
|
677
|
+
.map((param) => `${param.name}: data.${param.name}`)
|
|
678
|
+
.join(',')}});
|
|
679
|
+
const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
|
|
680
|
+
return result.data;
|
|
681
|
+
},
|
|
682
|
+
props?.options
|
|
683
|
+
)};`;
|
|
684
|
+
}
|
|
685
|
+
if (requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
|
|
686
|
+
output += `
|
|
687
|
+
type ${componentName}QueryVariables = ${requestBodyComponent};
|
|
688
|
+
interface ${componentName}QueryProps<T = ${genericsTypes}> extends ${componentName}QueryVariables {
|
|
689
|
+
options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
|
|
690
|
+
}
|
|
691
|
+
export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...body }: ${componentName}QueryProps<T>) {
|
|
692
|
+
return useQuery(use${componentName}Query.queryKey(body), async () => use${componentName}Query.fetch(body), options
|
|
693
|
+
);}
|
|
694
|
+
|
|
695
|
+
use${componentName}Query.fetch = async (body: Omit<${componentName}QueryProps, 'options'>) => {
|
|
696
|
+
const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
|
|
697
|
+
return result.data
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
|
|
701
|
+
|
|
702
|
+
use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
|
|
703
|
+
|
|
704
|
+
type ${componentName}MutationVariables = ${requestBodyComponent};
|
|
705
|
+
|
|
706
|
+
interface ${componentName}MutationProps<T> {
|
|
707
|
+
options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
|
|
708
|
+
}
|
|
709
|
+
export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
|
|
710
|
+
return useMutation(async (body) => {
|
|
711
|
+
const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
|
|
712
|
+
return result.data
|
|
713
|
+
},
|
|
714
|
+
props?.options
|
|
715
|
+
)};`;
|
|
716
|
+
}
|
|
717
|
+
if (requestBodyComponent && paramsInPath.length && !queryParam && headerParam) {
|
|
718
|
+
output += `// TODO: CODEGEN DOES NOT SUPPORT requestBodyComponent AND paramsInPath AND headerParam`;
|
|
719
|
+
}
|
|
595
720
|
return output;
|
|
596
721
|
};
|
|
597
722
|
exports.generateRestfulComponent = generateRestfulComponent;
|
|
598
723
|
/**
|
|
599
724
|
* Main entry of the generator. Generate react-query component from openAPI.
|
|
600
725
|
*/
|
|
601
|
-
const importOpenApi = async ({ data, format }) => {
|
|
726
|
+
const importOpenApi = async ({ data, format, apiDir, }) => {
|
|
602
727
|
const operationIds = [];
|
|
603
728
|
let specs = await importSpecs(data, format);
|
|
604
|
-
exports.resolveDiscriminator(specs);
|
|
729
|
+
(0, exports.resolveDiscriminator)(specs);
|
|
605
730
|
let output = `
|
|
606
731
|
import { useQuery, useMutation, UseQueryOptions, UseMutationOptions, QueryKey } from 'react-query';
|
|
607
732
|
import queryString from 'query-string';
|
|
608
733
|
import {AxiosError} from 'axios';
|
|
609
|
-
import { api } from '
|
|
734
|
+
import { api } from '${apiDir}';
|
|
610
735
|
`;
|
|
611
736
|
output += '\n\n// SCEHMAS\n';
|
|
612
|
-
output += exports.generateSchemasDefinition(specs.components && specs.components.schemas);
|
|
737
|
+
output += (0, exports.generateSchemasDefinition)(specs.components && specs.components.schemas);
|
|
613
738
|
output += '\n\n// RESPONSES\n';
|
|
614
|
-
output += exports.generateResponsesDefinition(specs.components && specs.components.responses);
|
|
739
|
+
output += (0, exports.generateResponsesDefinition)(specs.components && specs.components.responses);
|
|
615
740
|
output += '\n\n// REQUEST BODIES\n';
|
|
616
|
-
output += exports.generateRequestBodiesDefinition(specs.components && specs.components.requestBodies);
|
|
741
|
+
output += (0, exports.generateRequestBodiesDefinition)(specs.components && specs.components.requestBodies);
|
|
617
742
|
output += '\n\n// HOOKS\n';
|
|
618
743
|
Object.entries(specs.paths).forEach(([route, verbs]) => {
|
|
619
744
|
Object.entries(verbs).forEach(([verb, operation]) => {
|
|
620
745
|
if (['get', 'post', 'patch', 'put', 'delete'].includes(verb) && !operation.deprecated) {
|
|
621
|
-
output += exports.generateRestfulComponent(operation, verb, route, operationIds, verbs.parameters, specs.components);
|
|
746
|
+
output += (0, exports.generateRestfulComponent)(operation, verb, route, operationIds, verbs.parameters, specs.components);
|
|
622
747
|
}
|
|
623
748
|
});
|
|
624
749
|
});
|
package/lib/cjs/index.js
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.importSpecs = void 0;
|
|
4
3
|
const react_query_codegen_import_1 = require("./react-query-codegen-import");
|
|
5
|
-
|
|
4
|
+
exports.default = react_query_codegen_import_1.importSpecs;
|
|
@@ -7,22 +7,22 @@ exports.importSpecs = void 0;
|
|
|
7
7
|
const chalk_1 = __importDefault(require("chalk"));
|
|
8
8
|
const fs_1 = require("fs");
|
|
9
9
|
const path_1 = require("path");
|
|
10
|
-
const
|
|
10
|
+
const import_open_api_js_1 = require("./import-open-api.js");
|
|
11
11
|
const log = console.log; // tslint:disable-line:no-console
|
|
12
12
|
const createSuccessMessage = (backend) => chalk_1.default.green(`🎉 ${backend ? `[${backend}] ` : ''} Your OpenAPI spec has been converted into react query hooks`);
|
|
13
|
-
function importSpecs(
|
|
14
|
-
fs_1.readdir(
|
|
13
|
+
function importSpecs({ sourceDirectory, exportDirectory, apiDirectory, }) {
|
|
14
|
+
(0, fs_1.readdir)(sourceDirectory, function (err, filenames) {
|
|
15
15
|
if (err) {
|
|
16
16
|
throw err;
|
|
17
17
|
}
|
|
18
18
|
filenames.map(async (filename) => {
|
|
19
|
-
const data = fs_1.readFileSync(path_1.join(process.cwd(),
|
|
20
|
-
const { ext } = path_1.parse(
|
|
19
|
+
const data = (0, fs_1.readFileSync)((0, path_1.join)(process.cwd(), sourceDirectory + '/' + filename), 'utf-8');
|
|
20
|
+
const { ext } = (0, path_1.parse)(sourceDirectory + '/' + filename);
|
|
21
21
|
const format = ['.yaml', '.yml'].includes(ext.toLowerCase()) ? 'yaml' : 'json';
|
|
22
22
|
try {
|
|
23
23
|
const name = `useQueries${filename.split('.')[0]}.tsx`;
|
|
24
|
-
const fileExports = await
|
|
25
|
-
fs_1.writeFileSync(path_1.join(process.cwd(), `${
|
|
24
|
+
const fileExports = await (0, import_open_api_js_1.importOpenApi)({ data, format, apiDir: apiDirectory });
|
|
25
|
+
(0, fs_1.writeFileSync)((0, path_1.join)(process.cwd(), `${exportDirectory}/${name}`), fileExports);
|
|
26
26
|
log(createSuccessMessage(filename));
|
|
27
27
|
}
|
|
28
28
|
catch (error) {
|
|
@@ -1,11 +1,9 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
import set from 'lodash/set';
|
|
6
|
-
import uniq from 'lodash/uniq';
|
|
1
|
+
import _case from 'case';
|
|
2
|
+
import _ from 'lodash';
|
|
3
|
+
const { pascal } = _case;
|
|
4
|
+
const { uniq, get, groupBy, isEmpty, set } = _;
|
|
7
5
|
import swagger2openapi from 'swagger2openapi';
|
|
8
|
-
|
|
6
|
+
import yaml from 'js-yaml';
|
|
9
7
|
const IdentifierRegexp = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
|
|
10
8
|
/**
|
|
11
9
|
* Import and parse the openapi spec from a yaml/json
|
|
@@ -310,7 +308,7 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
|
|
|
310
308
|
const requestBodyTypes = getResReqTypes([['body', operation.requestBody]]);
|
|
311
309
|
const needAResponseComponent = true;
|
|
312
310
|
const paramsInPath = getParamsInPath(route).filter((param) => !(verb === 'delete' && param === lastParamInTheRoute));
|
|
313
|
-
const { query: queryParams = [], path: pathParams = [] } = groupBy([...parameters, ...(operation.parameters || [])].map((p) => {
|
|
311
|
+
const { query: queryParams = [], path: pathParams = [], header: headerParams = [] } = groupBy([...parameters, ...(operation.parameters || [])].map((p) => {
|
|
314
312
|
if (isReference(p)) {
|
|
315
313
|
return get(schemasComponents, p.$ref.replace('#/components/', '').replace('/', '.'));
|
|
316
314
|
}
|
|
@@ -335,6 +333,17 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
|
|
|
335
333
|
return `${formatDescription(p.description, 2)}${processedName}${p.required ? '' : '?'}: ${resolveValue(p.schema)}`;
|
|
336
334
|
})
|
|
337
335
|
.join(';\n ');
|
|
336
|
+
const headerType = headerParams
|
|
337
|
+
.map((p) => {
|
|
338
|
+
try {
|
|
339
|
+
const { name, required, schema } = headerParams.find((i) => i.name === p.name);
|
|
340
|
+
return `"${name}"${required ? '' : '?'}: ${resolveValue(schema)}`;
|
|
341
|
+
}
|
|
342
|
+
catch (err) {
|
|
343
|
+
throw new Error(`The path params ${p} can't be found in parameters (${operationId})`);
|
|
344
|
+
}
|
|
345
|
+
})
|
|
346
|
+
.join('; ');
|
|
338
347
|
// Retrieve the type of the param for delete verb
|
|
339
348
|
const lastParamInTheRouteDefinition = operation.parameters && lastParamInTheRoute
|
|
340
349
|
? operation.parameters.find((p) => {
|
|
@@ -359,10 +368,12 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
|
|
|
359
368
|
output += `
|
|
360
369
|
${needAResponseComponent ? `export ${typeOrInterface} ${responseTypes}` : ''}
|
|
361
370
|
`;
|
|
371
|
+
const headerParam = headerType && headerType !== 'void' ? `${headerType};` : '';
|
|
362
372
|
const queryParam = queryParamsType && queryParamsType !== 'void' ? `${queryParamsType}` : '';
|
|
363
373
|
const requestBodyComponent = requestBodyTypes && requestBodyTypes !== 'void' ? `${requestBodyTypes}` : '';
|
|
374
|
+
console.log(headerParam);
|
|
364
375
|
// QUERIES
|
|
365
|
-
if (!requestBodyComponent && paramsInPath.length && !queryParam) {
|
|
376
|
+
if (!requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
|
|
366
377
|
output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
|
|
367
378
|
${paramsTypes};
|
|
368
379
|
options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
|
|
@@ -396,7 +407,7 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
|
|
|
396
407
|
props?.options
|
|
397
408
|
)};`;
|
|
398
409
|
}
|
|
399
|
-
if (!requestBodyComponent && paramsInPath.length && queryParam) {
|
|
410
|
+
if (!requestBodyComponent && paramsInPath.length && queryParam && !headerParam) {
|
|
400
411
|
output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
|
|
401
412
|
${paramsTypes};
|
|
402
413
|
${queryParamsType};
|
|
@@ -435,7 +446,7 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
|
|
|
435
446
|
props?.options
|
|
436
447
|
)};`;
|
|
437
448
|
}
|
|
438
|
-
if (!requestBodyComponent && !paramsInPath.length && !queryParam) {
|
|
449
|
+
if (!requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
|
|
439
450
|
output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
|
|
440
451
|
options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
|
|
441
452
|
}
|
|
@@ -464,7 +475,7 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
|
|
|
464
475
|
props?.options
|
|
465
476
|
)};`;
|
|
466
477
|
}
|
|
467
|
-
if (!requestBodyComponent && !paramsInPath.length && queryParam) {
|
|
478
|
+
if (!requestBodyComponent && !paramsInPath.length && queryParam && !headerParam) {
|
|
468
479
|
output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
|
|
469
480
|
${queryParamsType};
|
|
470
481
|
options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
|
|
@@ -505,7 +516,7 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
|
|
|
505
516
|
props?.options
|
|
506
517
|
)};`;
|
|
507
518
|
}
|
|
508
|
-
if (requestBodyComponent && !paramsInPath.length && !queryParam) {
|
|
519
|
+
if (requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
|
|
509
520
|
output += `type ${componentName}QueryVariables = ${requestBodyComponent};
|
|
510
521
|
interface ${componentName}QueryProps<T = ${genericsTypes}> extends ${componentName}QueryVariables {
|
|
511
522
|
options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
|
|
@@ -536,7 +547,7 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
|
|
|
536
547
|
props?.options
|
|
537
548
|
)};`;
|
|
538
549
|
}
|
|
539
|
-
if (requestBodyComponent && paramsInPath.length && !queryParam) {
|
|
550
|
+
if (requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
|
|
540
551
|
output += `interface ${componentName}QueryProps<T = ${genericsTypes}> extends ${requestBodyComponent
|
|
541
552
|
.replace('{', '')
|
|
542
553
|
.replace('}', '')} {
|
|
@@ -547,7 +558,6 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
|
|
|
547
558
|
return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props), { enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
|
|
548
559
|
);}
|
|
549
560
|
|
|
550
|
-
// HEHEH
|
|
551
561
|
use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'>) => {
|
|
552
562
|
const {${paramsInPath.join(', ')}, ...body} = props
|
|
553
563
|
const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
|
|
@@ -558,7 +568,6 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
|
|
|
558
568
|
|
|
559
569
|
use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
|
|
560
570
|
|
|
561
|
-
|
|
562
571
|
`;
|
|
563
572
|
output += `type ${componentName}MutationVariables = {${paramsTypes}} & ${requestBodyComponent}
|
|
564
573
|
interface ${componentName}MutationProps<T> {
|
|
@@ -569,15 +578,131 @@ export const generateRestfulComponent = (operation, verb, route, operationIds, p
|
|
|
569
578
|
props?.options
|
|
570
579
|
)};`;
|
|
571
580
|
}
|
|
572
|
-
if (requestBodyComponent && queryParam) {
|
|
581
|
+
if (requestBodyComponent && queryParam && !headerParam) {
|
|
582
|
+
output += `// TODO: CODEGEN DOES NOT SUPPORT QUERYPARAM AND REQUESTBODY`;
|
|
583
|
+
}
|
|
584
|
+
if (requestBodyComponent && queryParam && headerParam) {
|
|
573
585
|
output += `// TODO: CODEGEN DOES NOT SUPPORT QUERYPARAM AND REQUESTBODY`;
|
|
574
586
|
}
|
|
587
|
+
if (!requestBodyComponent && paramsInPath.length && !queryParam && headerParam) {
|
|
588
|
+
output += `// TODO: CODEGEN DOES NOT SUPPORT paramsInPath AND headerParam`;
|
|
589
|
+
}
|
|
590
|
+
if (!requestBodyComponent && paramsInPath.length && queryParam && headerParam) {
|
|
591
|
+
output += `// TODO: CODEGEN DOES NOT SUPPORT paramsInPath AND headerParam AND headerParam`;
|
|
592
|
+
}
|
|
593
|
+
if (!requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
|
|
594
|
+
output += `
|
|
595
|
+
// HELLO
|
|
596
|
+
type ${componentName}HeaderVariables = {${headerParam}};
|
|
597
|
+
type ${componentName}QueryProps<T = ${genericsTypes}> = ${componentName}HeaderVariables & {
|
|
598
|
+
options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
|
|
599
|
+
}
|
|
600
|
+
export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
|
|
601
|
+
return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
|
|
602
|
+
{ enabled: !!props${headerParams.map((param) => `["${param.name}"]`).join(' && !!props')}, ...options }
|
|
603
|
+
);}
|
|
604
|
+
|
|
605
|
+
use${componentName}Query.fetch = async (headers: ${componentName}HeaderVariables) => {
|
|
606
|
+
const result = await api.${verb}<${genericsTypes}>(\`${route}\`, {headers: headers});
|
|
607
|
+
return result.data;
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
|
|
611
|
+
|
|
612
|
+
use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
|
|
613
|
+
|
|
614
|
+
type ${componentName}MutationProps<T> = {
|
|
615
|
+
options?: UseMutationOptions<${genericsTypes}, AxiosError, void, T>
|
|
616
|
+
}
|
|
617
|
+
export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
|
|
618
|
+
return useMutation(async () => {
|
|
619
|
+
const result = await api.${verb}<${genericsTypes}>(\`${route}\`);
|
|
620
|
+
return result.data;
|
|
621
|
+
},
|
|
622
|
+
props?.options
|
|
623
|
+
)};`;
|
|
624
|
+
}
|
|
625
|
+
if (!requestBodyComponent && !paramsInPath.length && queryParam && headerParam) {
|
|
626
|
+
output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
|
|
627
|
+
${queryParamsType};
|
|
628
|
+
options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
|
|
629
|
+
}
|
|
630
|
+
export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
|
|
631
|
+
return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
|
|
632
|
+
{ enabled: !!props.${queryParams.map((param) => param.name).join(' && !!props.')}, ...options }
|
|
633
|
+
);}
|
|
634
|
+
|
|
635
|
+
use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'>) => {
|
|
636
|
+
const params = queryString.stringify({${queryParams
|
|
637
|
+
.map((param) => `${param.name}: props.${param.name}`)
|
|
638
|
+
.join(',')}});
|
|
639
|
+
const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
|
|
640
|
+
return result.data;
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
|
|
644
|
+
|
|
645
|
+
use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
|
|
646
|
+
|
|
647
|
+
interface ${componentName}MutationVariables {
|
|
648
|
+
${queryParamsType}
|
|
649
|
+
}
|
|
650
|
+
interface ${componentName}MutationProps<T> {
|
|
651
|
+
options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
|
|
655
|
+
return useMutation(async (data) => {
|
|
656
|
+
const params = queryString.stringify({${queryParams
|
|
657
|
+
.map((param) => `${param.name}: data.${param.name}`)
|
|
658
|
+
.join(',')}});
|
|
659
|
+
const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
|
|
660
|
+
return result.data;
|
|
661
|
+
},
|
|
662
|
+
props?.options
|
|
663
|
+
)};`;
|
|
664
|
+
}
|
|
665
|
+
if (requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
|
|
666
|
+
output += `
|
|
667
|
+
type ${componentName}QueryVariables = ${requestBodyComponent};
|
|
668
|
+
interface ${componentName}QueryProps<T = ${genericsTypes}> extends ${componentName}QueryVariables {
|
|
669
|
+
options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
|
|
670
|
+
}
|
|
671
|
+
export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...body }: ${componentName}QueryProps<T>) {
|
|
672
|
+
return useQuery(use${componentName}Query.queryKey(body), async () => use${componentName}Query.fetch(body), options
|
|
673
|
+
);}
|
|
674
|
+
|
|
675
|
+
use${componentName}Query.fetch = async (body: Omit<${componentName}QueryProps, 'options'>) => {
|
|
676
|
+
const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
|
|
677
|
+
return result.data
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
|
|
681
|
+
|
|
682
|
+
use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
|
|
683
|
+
|
|
684
|
+
type ${componentName}MutationVariables = ${requestBodyComponent};
|
|
685
|
+
|
|
686
|
+
interface ${componentName}MutationProps<T> {
|
|
687
|
+
options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
|
|
688
|
+
}
|
|
689
|
+
export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
|
|
690
|
+
return useMutation(async (body) => {
|
|
691
|
+
const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
|
|
692
|
+
return result.data
|
|
693
|
+
},
|
|
694
|
+
props?.options
|
|
695
|
+
)};`;
|
|
696
|
+
}
|
|
697
|
+
if (requestBodyComponent && paramsInPath.length && !queryParam && headerParam) {
|
|
698
|
+
output += `// TODO: CODEGEN DOES NOT SUPPORT requestBodyComponent AND paramsInPath AND headerParam`;
|
|
699
|
+
}
|
|
575
700
|
return output;
|
|
576
701
|
};
|
|
577
702
|
/**
|
|
578
703
|
* Main entry of the generator. Generate react-query component from openAPI.
|
|
579
704
|
*/
|
|
580
|
-
export const importOpenApi = async ({ data, format }) => {
|
|
705
|
+
export const importOpenApi = async ({ data, format, apiDir, }) => {
|
|
581
706
|
const operationIds = [];
|
|
582
707
|
let specs = await importSpecs(data, format);
|
|
583
708
|
resolveDiscriminator(specs);
|
|
@@ -585,7 +710,7 @@ export const importOpenApi = async ({ data, format }) => {
|
|
|
585
710
|
import { useQuery, useMutation, UseQueryOptions, UseMutationOptions, QueryKey } from 'react-query';
|
|
586
711
|
import queryString from 'query-string';
|
|
587
712
|
import {AxiosError} from 'axios';
|
|
588
|
-
import { api } from '
|
|
713
|
+
import { api } from '${apiDir}';
|
|
589
714
|
`;
|
|
590
715
|
output += '\n\n// SCEHMAS\n';
|
|
591
716
|
output += generateSchemasDefinition(specs.components && specs.components.schemas);
|
package/lib/esm/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { importSpecs } from './react-query-codegen-import';
|
|
2
|
-
export
|
|
2
|
+
export default importSpecs;
|
|
@@ -1,22 +1,22 @@
|
|
|
1
1
|
import chalk from 'chalk';
|
|
2
2
|
import { readFileSync, writeFileSync, readdir } from 'fs';
|
|
3
3
|
import { join, parse } from 'path';
|
|
4
|
-
import { importOpenApi } from './import-open-api';
|
|
4
|
+
import { importOpenApi } from './import-open-api.js';
|
|
5
5
|
const log = console.log; // tslint:disable-line:no-console
|
|
6
6
|
const createSuccessMessage = (backend) => chalk.green(`🎉 ${backend ? `[${backend}] ` : ''} Your OpenAPI spec has been converted into react query hooks`);
|
|
7
|
-
export function importSpecs(
|
|
8
|
-
readdir(
|
|
7
|
+
export function importSpecs({ sourceDirectory, exportDirectory, apiDirectory, }) {
|
|
8
|
+
readdir(sourceDirectory, function (err, filenames) {
|
|
9
9
|
if (err) {
|
|
10
10
|
throw err;
|
|
11
11
|
}
|
|
12
12
|
filenames.map(async (filename) => {
|
|
13
|
-
const data = readFileSync(join(process.cwd(),
|
|
14
|
-
const { ext } = parse(
|
|
13
|
+
const data = readFileSync(join(process.cwd(), sourceDirectory + '/' + filename), 'utf-8');
|
|
14
|
+
const { ext } = parse(sourceDirectory + '/' + filename);
|
|
15
15
|
const format = ['.yaml', '.yml'].includes(ext.toLowerCase()) ? 'yaml' : 'json';
|
|
16
16
|
try {
|
|
17
17
|
const name = `useQueries${filename.split('.')[0]}.tsx`;
|
|
18
|
-
const fileExports = await importOpenApi({ data, format });
|
|
19
|
-
writeFileSync(join(process.cwd(), `${
|
|
18
|
+
const fileExports = await importOpenApi({ data, format, apiDir: apiDirectory });
|
|
19
|
+
writeFileSync(join(process.cwd(), `${exportDirectory}/${name}`), fileExports);
|
|
20
20
|
log(createSuccessMessage(filename));
|
|
21
21
|
}
|
|
22
22
|
catch (error) {
|
package/package.json
CHANGED
|
@@ -1,45 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "react-query-lightbase-codegen",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.8",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"main": "./lib/cjs/index.js",
|
|
6
6
|
"module": "./lib/esm/index.js",
|
|
7
7
|
"files": [
|
|
8
8
|
"lib/"
|
|
9
9
|
],
|
|
10
|
+
"type": "module",
|
|
10
11
|
"scripts": {
|
|
11
12
|
"tsc": "tsc -p tsconfig.json && tsc -p tsconfig-cjs.json",
|
|
12
|
-
"test": "yarn tsc && node test/script.
|
|
13
|
+
"test": "yarn tsc && node test/script.mjs"
|
|
13
14
|
},
|
|
14
15
|
"dependencies": {
|
|
15
|
-
"axios": "
|
|
16
|
-
"case": "
|
|
17
|
-
"chalk": "
|
|
18
|
-
"
|
|
19
|
-
"
|
|
20
|
-
"
|
|
21
|
-
"
|
|
22
|
-
"
|
|
23
|
-
"
|
|
24
|
-
"
|
|
25
|
-
"
|
|
26
|
-
"swagger2openapi": "^7.0.8",
|
|
27
|
-
"yamljs": "^0.3.0"
|
|
16
|
+
"axios": "0.27.2",
|
|
17
|
+
"case": "1.6.3",
|
|
18
|
+
"chalk": "5.0.1",
|
|
19
|
+
"js-yaml": "4.1.0",
|
|
20
|
+
"lodash": "4.17.21",
|
|
21
|
+
"openapi3-ts": "2.0.2",
|
|
22
|
+
"qs": "6.10.3",
|
|
23
|
+
"query-string": "7.1.1",
|
|
24
|
+
"react-query": "3.39.0",
|
|
25
|
+
"swagger2openapi": "7.0.8",
|
|
26
|
+
"yamljs": "0.3.0"
|
|
28
27
|
},
|
|
29
28
|
"devDependencies": {
|
|
30
|
-
"@
|
|
31
|
-
"@
|
|
32
|
-
"@types/
|
|
33
|
-
"@types/lodash": "
|
|
34
|
-
"@types/node": "
|
|
35
|
-
"@types/qs": "
|
|
36
|
-
"@types/
|
|
37
|
-
"
|
|
38
|
-
"
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
"
|
|
42
|
-
"
|
|
43
|
-
"
|
|
29
|
+
"@babel/eslint-parser": "7.17.0",
|
|
30
|
+
"@react-native-community/eslint-config": "3.0.1",
|
|
31
|
+
"@types/js-yaml": "^4.0.5",
|
|
32
|
+
"@types/lodash": "4.14.182",
|
|
33
|
+
"@types/node": "17.0.32",
|
|
34
|
+
"@types/qs": "6.9.7",
|
|
35
|
+
"@types/yamljs": "0.2.31",
|
|
36
|
+
"prettier": "2.6.2",
|
|
37
|
+
"typescript": "4.6.4"
|
|
38
|
+
},
|
|
39
|
+
"resolutions": {
|
|
40
|
+
"@typescript-eslint/eslint-plugin": "5.15.0",
|
|
41
|
+
"@typescript-eslint/parser": "5.15.0",
|
|
42
|
+
"eslint-plugin-flowtype": "8.0.0",
|
|
43
|
+
"@types/react": "17.0.44"
|
|
44
44
|
}
|
|
45
45
|
}
|