react-query-lightbase-codegen 0.0.2 → 0.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/lib/cjs/index.js +5 -0
- package/lib/cjs/react-query-codegen-import.js +44 -0
- package/lib/cjs/react-query-codegen.js +17 -0
- package/lib/cjs/scripts/import-open-api.js +626 -0
- package/lib/cjs/types.js +2 -0
- package/lib/esm/index.js +2 -0
- package/lib/esm/react-query-codegen-import.js +39 -0
- package/lib/esm/react-query-codegen.js +10 -0
- package/lib/esm/scripts/import-open-api.js +605 -0
- package/lib/esm/types.js +1 -0
- package/package.json +7 -2
- package/.eslintrc.js +0 -7
- package/.prettierrc +0 -8
- package/rollup.config.js +0 -15
- package/src/mobile-api.yaml +0 -1550
- package/src/react-query-codegen-import.ts +0 -57
- package/src/react-query-codegen.ts +0 -10
- package/src/scripts/import-open-api.ts +0 -739
- package/src/types.ts +0 -12
- package/tsconfig.json +0 -22
- package/types/swagger2openapi.d.ts +0 -11
|
@@ -0,0 +1,626 @@
|
|
|
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.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 get_1 = __importDefault(require("lodash/get"));
|
|
9
|
+
const groupBy_1 = __importDefault(require("lodash/groupBy"));
|
|
10
|
+
const isEmpty_1 = __importDefault(require("lodash/isEmpty"));
|
|
11
|
+
const set_1 = __importDefault(require("lodash/set"));
|
|
12
|
+
const uniq_1 = __importDefault(require("lodash/uniq"));
|
|
13
|
+
const swagger2openapi_1 = __importDefault(require("swagger2openapi"));
|
|
14
|
+
const yaml = require('js-yaml');
|
|
15
|
+
const IdentifierRegexp = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
|
|
16
|
+
/**
|
|
17
|
+
* Import and parse the openapi spec from a yaml/json
|
|
18
|
+
*/
|
|
19
|
+
const importSpecs = (data, extension) => {
|
|
20
|
+
const schema = extension === 'yaml' ? yaml.load(data) : JSON.parse(data);
|
|
21
|
+
return new Promise((resolve, reject) => {
|
|
22
|
+
if (!schema.openapi || !schema.openapi.startsWith('3.')) {
|
|
23
|
+
swagger2openapi_1.default.convertObj(schema, {}, (err, convertedObj) => {
|
|
24
|
+
if (err) {
|
|
25
|
+
reject(err);
|
|
26
|
+
}
|
|
27
|
+
else {
|
|
28
|
+
resolve(convertedObj.openapi);
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
else {
|
|
33
|
+
resolve(schema);
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* Discriminator helper for `ReferenceObject`
|
|
39
|
+
*/
|
|
40
|
+
const isReference = (property) => {
|
|
41
|
+
return Boolean(property.$ref);
|
|
42
|
+
};
|
|
43
|
+
exports.isReference = isReference;
|
|
44
|
+
/**
|
|
45
|
+
* Return the typescript equivalent of open-api data type
|
|
46
|
+
*/
|
|
47
|
+
const getScalar = (item) => {
|
|
48
|
+
const nullable = item.nullable ? ' | null' : '';
|
|
49
|
+
switch (item.type) {
|
|
50
|
+
case 'number':
|
|
51
|
+
case 'integer':
|
|
52
|
+
return 'number' + nullable;
|
|
53
|
+
case 'boolean':
|
|
54
|
+
return 'boolean' + nullable;
|
|
55
|
+
case 'array':
|
|
56
|
+
return exports.getArray(item) + nullable;
|
|
57
|
+
case 'string':
|
|
58
|
+
return (item.enum ? `"${item.enum.join(`" | "`)}"` : 'string') + nullable;
|
|
59
|
+
case 'object':
|
|
60
|
+
default:
|
|
61
|
+
return exports.getObject(item) + nullable;
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
exports.getScalar = getScalar;
|
|
65
|
+
/**
|
|
66
|
+
* Return the output type from the $ref
|
|
67
|
+
*/
|
|
68
|
+
const getRef = ($ref) => {
|
|
69
|
+
if ($ref.startsWith('#/components/schemas')) {
|
|
70
|
+
return case_1.pascal($ref.replace('#/components/schemas/', ''));
|
|
71
|
+
}
|
|
72
|
+
else if ($ref.startsWith('#/components/responses')) {
|
|
73
|
+
return case_1.pascal($ref.replace('#/components/responses/', '')) + 'Response';
|
|
74
|
+
}
|
|
75
|
+
else if ($ref.startsWith('#/components/parameters')) {
|
|
76
|
+
return case_1.pascal($ref.replace('#/components/parameters/', '')) + 'Parameter';
|
|
77
|
+
}
|
|
78
|
+
else if ($ref.startsWith('#/components/requestBodies')) {
|
|
79
|
+
return case_1.pascal($ref.replace('#/components/requestBodies/', '')) + 'RequestBody';
|
|
80
|
+
}
|
|
81
|
+
else {
|
|
82
|
+
throw new Error('This library only resolve $ref that are include into `#/components/*` for now');
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
exports.getRef = getRef;
|
|
86
|
+
/**
|
|
87
|
+
* Return the output type from an array
|
|
88
|
+
*/
|
|
89
|
+
const getArray = (item) => {
|
|
90
|
+
if (item.items) {
|
|
91
|
+
if (!exports.isReference(item.items) && (item.items.oneOf || item.items.allOf || item.items.enum)) {
|
|
92
|
+
return `(${exports.resolveValue(item.items)})[]`;
|
|
93
|
+
}
|
|
94
|
+
else {
|
|
95
|
+
return `${exports.resolveValue(item.items)}[]`;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
else {
|
|
99
|
+
throw new Error('All arrays must have an `items` key define');
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
exports.getArray = getArray;
|
|
103
|
+
/**
|
|
104
|
+
* Return the output type from an object
|
|
105
|
+
*/
|
|
106
|
+
const getObject = (item) => {
|
|
107
|
+
if (exports.isReference(item)) {
|
|
108
|
+
return exports.getRef(item.$ref);
|
|
109
|
+
}
|
|
110
|
+
if (item.allOf) {
|
|
111
|
+
return item.allOf.map(exports.resolveValue).join(' & ');
|
|
112
|
+
}
|
|
113
|
+
if (item.oneOf) {
|
|
114
|
+
return item.oneOf.map(exports.resolveValue).join(' | ');
|
|
115
|
+
}
|
|
116
|
+
if (!item.type && !item.properties && !item.additionalProperties) {
|
|
117
|
+
return '{}';
|
|
118
|
+
}
|
|
119
|
+
// Free form object (https://swagger.io/docs/specification/data-models/data-types/#free-form)
|
|
120
|
+
if (item.type === 'object' &&
|
|
121
|
+
!item.properties &&
|
|
122
|
+
(!item.additionalProperties || item.additionalProperties === true || isEmpty_1.default(item.additionalProperties))) {
|
|
123
|
+
return '{[key: string]: any}';
|
|
124
|
+
}
|
|
125
|
+
// Consolidation of item.properties & item.additionalProperties
|
|
126
|
+
let output = '{\n';
|
|
127
|
+
if (item.properties) {
|
|
128
|
+
output += Object.entries(item.properties)
|
|
129
|
+
.map(([key, prop]) => {
|
|
130
|
+
const doc = exports.isReference(prop) ? '' : exports.formatDescription(prop.description, 2);
|
|
131
|
+
const isRequired = (item.required || []).includes(key);
|
|
132
|
+
const processedKey = IdentifierRegexp.test(key) ? key : `"${key}"`;
|
|
133
|
+
return ` ${doc}${processedKey}${isRequired ? '' : '?'}: ${exports.resolveValue(prop)};`;
|
|
134
|
+
})
|
|
135
|
+
.join('\n');
|
|
136
|
+
}
|
|
137
|
+
if (item.additionalProperties) {
|
|
138
|
+
if (item.properties) {
|
|
139
|
+
output += '\n';
|
|
140
|
+
}
|
|
141
|
+
output += ` [key: string]: ${item.additionalProperties === true ? 'any' : exports.resolveValue(item.additionalProperties)};`;
|
|
142
|
+
}
|
|
143
|
+
if (item.properties || item.additionalProperties) {
|
|
144
|
+
if (output === '{\n') {
|
|
145
|
+
return '{}';
|
|
146
|
+
}
|
|
147
|
+
return output + '\n}';
|
|
148
|
+
}
|
|
149
|
+
return item.type === 'object' ? '{[key: string]: any}' : 'any';
|
|
150
|
+
};
|
|
151
|
+
exports.getObject = getObject;
|
|
152
|
+
/**
|
|
153
|
+
* Resolve the value of a schema object to a proper type definition.
|
|
154
|
+
*/
|
|
155
|
+
const resolveValue = (schema) => exports.isReference(schema) ? exports.getRef(schema.$ref) : exports.getScalar(schema);
|
|
156
|
+
exports.resolveValue = resolveValue;
|
|
157
|
+
/**
|
|
158
|
+
* Extract responses / request types from open-api specs
|
|
159
|
+
*/
|
|
160
|
+
const getResReqTypes = (responsesOrRequests) => uniq_1.default(responsesOrRequests.map(([_, res]) => {
|
|
161
|
+
if (!res) {
|
|
162
|
+
return 'void';
|
|
163
|
+
}
|
|
164
|
+
if (exports.isReference(res)) {
|
|
165
|
+
return exports.getRef(res.$ref);
|
|
166
|
+
}
|
|
167
|
+
if (res.content) {
|
|
168
|
+
for (let contentType of Object.keys(res.content)) {
|
|
169
|
+
if (contentType.startsWith('application/json') ||
|
|
170
|
+
contentType.startsWith('application/octet-stream')) {
|
|
171
|
+
const schema = res.content[contentType].schema;
|
|
172
|
+
return exports.resolveValue(schema);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return 'void';
|
|
176
|
+
}
|
|
177
|
+
return 'void';
|
|
178
|
+
})).join(' | ');
|
|
179
|
+
exports.getResReqTypes = getResReqTypes;
|
|
180
|
+
/**
|
|
181
|
+
* Return every params in a path
|
|
182
|
+
*
|
|
183
|
+
* @example
|
|
184
|
+
* ```
|
|
185
|
+
* getParamsInPath("/pet/{category}/{name}/");
|
|
186
|
+
* // => ["category", "name"]
|
|
187
|
+
* ```
|
|
188
|
+
*/
|
|
189
|
+
const getParamsInPath = (path) => {
|
|
190
|
+
let n;
|
|
191
|
+
const output = [];
|
|
192
|
+
const templatePathRegex = /\{(\w+)}/g;
|
|
193
|
+
while ((n = templatePathRegex.exec(path)) !== null) {
|
|
194
|
+
output.push(n[1]);
|
|
195
|
+
}
|
|
196
|
+
return output;
|
|
197
|
+
};
|
|
198
|
+
exports.getParamsInPath = getParamsInPath;
|
|
199
|
+
/**
|
|
200
|
+
* Generate the interface string
|
|
201
|
+
*/
|
|
202
|
+
const generateInterface = (name, schema) => {
|
|
203
|
+
const scalar = exports.getScalar(schema);
|
|
204
|
+
return `${exports.formatDescription(schema.description)}export interface ${case_1.pascal(name)} ${scalar}`;
|
|
205
|
+
};
|
|
206
|
+
exports.generateInterface = generateInterface;
|
|
207
|
+
/**
|
|
208
|
+
* Propagate every `discriminator.propertyName` mapping to the original ref
|
|
209
|
+
*
|
|
210
|
+
* Note: This method directly mutate the `specs` object.
|
|
211
|
+
*/
|
|
212
|
+
const resolveDiscriminator = (specs) => {
|
|
213
|
+
if (specs.components && specs.components.schemas) {
|
|
214
|
+
Object.values(specs.components.schemas).forEach((schema) => {
|
|
215
|
+
if (exports.isReference(schema) || !schema.discriminator || !schema.discriminator.mapping) {
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
const { mapping, propertyName } = schema.discriminator;
|
|
219
|
+
Object.entries(mapping).forEach(([name, ref]) => {
|
|
220
|
+
if (!ref.startsWith('#/components/schemas/')) {
|
|
221
|
+
throw new Error('Discriminator mapping outside of `#/components/schemas` is not supported');
|
|
222
|
+
}
|
|
223
|
+
set_1.default(specs, `components.schemas.${ref.slice('#/components/schemas/'.length)}.properties.${propertyName}.enum`, [name]);
|
|
224
|
+
});
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
exports.resolveDiscriminator = resolveDiscriminator;
|
|
229
|
+
/**
|
|
230
|
+
* Extract all types from #/components/schemas
|
|
231
|
+
*/
|
|
232
|
+
const generateSchemasDefinition = (schemas = {}) => {
|
|
233
|
+
if (isEmpty_1.default(schemas)) {
|
|
234
|
+
return '';
|
|
235
|
+
}
|
|
236
|
+
return (Object.entries(schemas)
|
|
237
|
+
.map(([name, schema]) => !exports.isReference(schema) &&
|
|
238
|
+
(!schema.type || schema.type === 'object') &&
|
|
239
|
+
!schema.allOf &&
|
|
240
|
+
!schema.oneOf &&
|
|
241
|
+
!exports.isReference(schema) &&
|
|
242
|
+
!schema.nullable
|
|
243
|
+
? exports.generateInterface(name, schema)
|
|
244
|
+
: `${exports.formatDescription(exports.isReference(schema) ? undefined : schema.description)}export type ${case_1.pascal(name)} = ${exports.resolveValue(schema)};`)
|
|
245
|
+
.join('\n\n') + '\n');
|
|
246
|
+
};
|
|
247
|
+
exports.generateSchemasDefinition = generateSchemasDefinition;
|
|
248
|
+
/**
|
|
249
|
+
* Extract all types from #/components/requestBodies
|
|
250
|
+
*/
|
|
251
|
+
const generateRequestBodiesDefinition = (requestBodies = {}) => {
|
|
252
|
+
if (isEmpty_1.default(requestBodies)) {
|
|
253
|
+
return '';
|
|
254
|
+
}
|
|
255
|
+
return ('\n' +
|
|
256
|
+
Object.entries(requestBodies)
|
|
257
|
+
.map(([name, requestBody]) => {
|
|
258
|
+
const doc = exports.isReference(requestBody) ? '' : exports.formatDescription(requestBody.description);
|
|
259
|
+
const type = exports.getResReqTypes([['', requestBody]]);
|
|
260
|
+
const isEmptyInterface = type === '{}';
|
|
261
|
+
if (isEmptyInterface) {
|
|
262
|
+
return `export interface ${case_1.pascal(name)}RequestBody ${type}`;
|
|
263
|
+
}
|
|
264
|
+
else if (type.includes('{') && !type.includes('|') && !type.includes('&')) {
|
|
265
|
+
return `${doc}export interface ${case_1.pascal(name)}RequestBody ${type}`;
|
|
266
|
+
}
|
|
267
|
+
else {
|
|
268
|
+
return `${doc}export type ${case_1.pascal(name)}RequestBody = ${type};`;
|
|
269
|
+
}
|
|
270
|
+
})
|
|
271
|
+
.join('\n\n') +
|
|
272
|
+
'\n');
|
|
273
|
+
};
|
|
274
|
+
exports.generateRequestBodiesDefinition = generateRequestBodiesDefinition;
|
|
275
|
+
/**
|
|
276
|
+
* Extract all types from #/components/responses
|
|
277
|
+
*/
|
|
278
|
+
const generateResponsesDefinition = (responses = {}) => {
|
|
279
|
+
if (isEmpty_1.default(responses)) {
|
|
280
|
+
return '';
|
|
281
|
+
}
|
|
282
|
+
return ('\n' +
|
|
283
|
+
Object.entries(responses)
|
|
284
|
+
.map(([name, response]) => {
|
|
285
|
+
const doc = exports.isReference(response) ? '' : exports.formatDescription(response.description);
|
|
286
|
+
const type = exports.getResReqTypes([['', response]]);
|
|
287
|
+
const isEmptyInterface = type === '{}';
|
|
288
|
+
if (isEmptyInterface) {
|
|
289
|
+
return `export interface RQ${case_1.pascal(name)}Response ${type}`;
|
|
290
|
+
}
|
|
291
|
+
else if (type.includes('{') && !type.includes('|') && !type.includes('&')) {
|
|
292
|
+
return `${doc}export interface RQ${case_1.pascal(name)}Response ${type}`;
|
|
293
|
+
}
|
|
294
|
+
else {
|
|
295
|
+
return `${doc}export type RQ${case_1.pascal(name)}Response = ${type};`;
|
|
296
|
+
}
|
|
297
|
+
})
|
|
298
|
+
.join('\n\n') +
|
|
299
|
+
'\n');
|
|
300
|
+
};
|
|
301
|
+
exports.generateResponsesDefinition = generateResponsesDefinition;
|
|
302
|
+
/**
|
|
303
|
+
* Format a description to code documentation.
|
|
304
|
+
*/
|
|
305
|
+
const formatDescription = (description, tabSize = 0) => description
|
|
306
|
+
? `/**\n${description
|
|
307
|
+
.split('\n')
|
|
308
|
+
.map((i) => `${' '.repeat(tabSize)} * ${i}`)
|
|
309
|
+
.join('\n')}\n${' '.repeat(tabSize)} */\n${' '.repeat(tabSize)}`
|
|
310
|
+
: '';
|
|
311
|
+
exports.formatDescription = formatDescription;
|
|
312
|
+
/**
|
|
313
|
+
* Generate a react-query component from openapi operation specs
|
|
314
|
+
*/
|
|
315
|
+
const generateRestfulComponent = (operation, verb, route, operationIds, parameters = [], schemasComponents) => {
|
|
316
|
+
if (!operation.operationId) {
|
|
317
|
+
throw new Error(`Every path must have a operationId - No operationId set for ${verb} ${route}`);
|
|
318
|
+
}
|
|
319
|
+
if (operationIds.includes(operation.operationId)) {
|
|
320
|
+
throw new Error(`"${operation.operationId}" is duplicated in your schema definition!`);
|
|
321
|
+
}
|
|
322
|
+
operationIds.push(operation.operationId);
|
|
323
|
+
route = route.replace(/\{/g, '${'); // `/pet/{id}` => `/pet/${id}`
|
|
324
|
+
// Remove the last param of the route if we are in the DELETE case
|
|
325
|
+
let lastParamInTheRoute = null;
|
|
326
|
+
const componentName = case_1.pascal(operation.operationId);
|
|
327
|
+
const isOk = ([statusCode]) => statusCode.toString().startsWith('2');
|
|
328
|
+
const responseTypes = exports.getResReqTypes(Object.entries(operation.responses).filter(isOk)) || 'void';
|
|
329
|
+
const requestBodyTypes = exports.getResReqTypes([['body', operation.requestBody]]);
|
|
330
|
+
const needAResponseComponent = true;
|
|
331
|
+
const paramsInPath = exports.getParamsInPath(route).filter((param) => !(verb === 'delete' && param === lastParamInTheRoute));
|
|
332
|
+
const { query: queryParams = [], path: pathParams = [] } = groupBy_1.default([...parameters, ...(operation.parameters || [])].map((p) => {
|
|
333
|
+
if (exports.isReference(p)) {
|
|
334
|
+
return get_1.default(schemasComponents, p.$ref.replace('#/components/', '').replace('/', '.'));
|
|
335
|
+
}
|
|
336
|
+
else {
|
|
337
|
+
return p;
|
|
338
|
+
}
|
|
339
|
+
}), 'in');
|
|
340
|
+
const paramsTypes = paramsInPath
|
|
341
|
+
.map((p) => {
|
|
342
|
+
try {
|
|
343
|
+
const { name, required, schema } = pathParams.find((i) => i.name === p);
|
|
344
|
+
return `${name}${required ? '' : '?'}: ${exports.resolveValue(schema)}`;
|
|
345
|
+
}
|
|
346
|
+
catch (err) {
|
|
347
|
+
throw new Error(`The path params ${p} can't be found in parameters (${operation.operationId})`);
|
|
348
|
+
}
|
|
349
|
+
})
|
|
350
|
+
.join('; ');
|
|
351
|
+
const queryParamsType = queryParams
|
|
352
|
+
.map((p) => {
|
|
353
|
+
const processedName = IdentifierRegexp.test(p.name) ? p.name : `"${p.name}"`;
|
|
354
|
+
return `${exports.formatDescription(p.description, 2)}${processedName}${p.required ? '' : '?'}: ${exports.resolveValue(p.schema)}`;
|
|
355
|
+
})
|
|
356
|
+
.join(';\n ');
|
|
357
|
+
// Retrieve the type of the param for delete verb
|
|
358
|
+
const lastParamInTheRouteDefinition = operation.parameters && lastParamInTheRoute
|
|
359
|
+
? operation.parameters.find((p) => {
|
|
360
|
+
if (exports.isReference(p)) {
|
|
361
|
+
return false;
|
|
362
|
+
}
|
|
363
|
+
return p.name === lastParamInTheRoute;
|
|
364
|
+
}) // Reference is not possible
|
|
365
|
+
: { schema: { type: 'string' } };
|
|
366
|
+
if (!lastParamInTheRouteDefinition) {
|
|
367
|
+
throw new Error(`The path params ${lastParamInTheRoute} can't be found in parameters (${operation.operationId})`);
|
|
368
|
+
}
|
|
369
|
+
let genericsTypes = `${needAResponseComponent ? componentName + 'Res' : responseTypes}`;
|
|
370
|
+
if (verb !== 'get') {
|
|
371
|
+
genericsTypes = `${needAResponseComponent ? componentName + 'Res' : responseTypes}`;
|
|
372
|
+
}
|
|
373
|
+
const description = exports.formatDescription(operation.summary && operation.description
|
|
374
|
+
? `${operation.summary}\n\n${operation.description}`
|
|
375
|
+
: `${operation.summary || ''}${operation.description || ''}`);
|
|
376
|
+
let output = `\n\n${description}`;
|
|
377
|
+
const typeOrInterface = `type ${componentName}Res =`;
|
|
378
|
+
output += `
|
|
379
|
+
${needAResponseComponent ? `export ${typeOrInterface} ${responseTypes}` : ''}
|
|
380
|
+
`;
|
|
381
|
+
const queryParam = queryParamsType && queryParamsType !== 'void' ? `${queryParamsType}` : '';
|
|
382
|
+
const requestBodyComponent = requestBodyTypes && requestBodyTypes !== 'void' ? `${requestBodyTypes}` : '';
|
|
383
|
+
// QUERIES
|
|
384
|
+
if (!requestBodyComponent && paramsInPath.length && !queryParam) {
|
|
385
|
+
output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
|
|
386
|
+
${paramsTypes};
|
|
387
|
+
options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
|
|
388
|
+
}
|
|
389
|
+
export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
|
|
390
|
+
return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
|
|
391
|
+
{ enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
|
|
392
|
+
);}
|
|
393
|
+
|
|
394
|
+
use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'> ) => {
|
|
395
|
+
const result = await api.${verb}<${genericsTypes}>(\`${route.replace(/\{/g, '{props.')}\`);
|
|
396
|
+
return result.data;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
|
|
400
|
+
|
|
401
|
+
use${componentName}Query.queryKey = (params: {${paramsTypes}} ): QueryKey => [...use${componentName}Query.baseKey(), params];
|
|
402
|
+
|
|
403
|
+
`;
|
|
404
|
+
output += `interface ${componentName}MutationVariables {
|
|
405
|
+
${paramsTypes}
|
|
406
|
+
}
|
|
407
|
+
interface ${componentName}MutationProps<T> {
|
|
408
|
+
options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
|
|
409
|
+
}
|
|
410
|
+
export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
|
|
411
|
+
return useMutation(async ({${paramsInPath.join(', ')}}) => {
|
|
412
|
+
const result = await api.${verb}<${genericsTypes}>(\`${route}\`)
|
|
413
|
+
return result.data
|
|
414
|
+
},
|
|
415
|
+
props?.options
|
|
416
|
+
)};`;
|
|
417
|
+
}
|
|
418
|
+
if (!requestBodyComponent && paramsInPath.length && queryParam) {
|
|
419
|
+
output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
|
|
420
|
+
${paramsTypes};
|
|
421
|
+
${queryParamsType};
|
|
422
|
+
options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
|
|
423
|
+
}
|
|
424
|
+
export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
|
|
425
|
+
return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props), { enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
|
|
426
|
+
);}
|
|
427
|
+
|
|
428
|
+
use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'>) => {
|
|
429
|
+
const {${paramsInPath.join(', ')}, ...queryParams} = props
|
|
430
|
+
const params = queryString.stringify(queryParams);
|
|
431
|
+
const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
|
|
432
|
+
return result.data;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
|
|
436
|
+
|
|
437
|
+
use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'>): QueryKey => [...use${componentName}Query.baseKey(), params];
|
|
438
|
+
|
|
439
|
+
`;
|
|
440
|
+
output += `interface ${componentName}MutationVariables {
|
|
441
|
+
${paramsTypes}
|
|
442
|
+
${queryParamsType}
|
|
443
|
+
}
|
|
444
|
+
interface ${componentName}MutationProps<T> {
|
|
445
|
+
options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
|
|
446
|
+
}
|
|
447
|
+
export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
|
|
448
|
+
return useMutation(async (data) => {
|
|
449
|
+
const {${paramsInPath.join(', ')}, ...queryParams} = data
|
|
450
|
+
const params = queryString.stringify(queryParams);
|
|
451
|
+
const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
|
|
452
|
+
return result.data
|
|
453
|
+
},
|
|
454
|
+
props?.options
|
|
455
|
+
)};`;
|
|
456
|
+
}
|
|
457
|
+
if (!requestBodyComponent && !paramsInPath.length && !queryParam) {
|
|
458
|
+
output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
|
|
459
|
+
options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
|
|
460
|
+
}
|
|
461
|
+
export function use${componentName}Query<T = ${genericsTypes}>(props?: ${componentName}QueryProps<T>) {
|
|
462
|
+
return useQuery(use${componentName}Query.queryKey(), use${componentName}Query.fetch, props?.options
|
|
463
|
+
);}
|
|
464
|
+
|
|
465
|
+
use${componentName}Query.fetch = async () => {
|
|
466
|
+
const result = await api.${verb}<${genericsTypes}>(\`${route}\`);
|
|
467
|
+
return result.data;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
|
|
471
|
+
|
|
472
|
+
use${componentName}Query.queryKey = (): QueryKey => use${componentName}Query.baseKey()
|
|
473
|
+
|
|
474
|
+
`;
|
|
475
|
+
output += `interface ${componentName}MutationProps<T> {
|
|
476
|
+
options?: UseMutationOptions<${genericsTypes}, AxiosError, void, T>
|
|
477
|
+
}
|
|
478
|
+
export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
|
|
479
|
+
return useMutation(async () => {
|
|
480
|
+
const result = await api.${verb}<${genericsTypes}>(\`${route}\`);
|
|
481
|
+
return result.data;
|
|
482
|
+
},
|
|
483
|
+
props?.options
|
|
484
|
+
)};`;
|
|
485
|
+
}
|
|
486
|
+
if (!requestBodyComponent && !paramsInPath.length && queryParam) {
|
|
487
|
+
output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
|
|
488
|
+
${queryParamsType};
|
|
489
|
+
options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
|
|
490
|
+
}
|
|
491
|
+
export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
|
|
492
|
+
return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
|
|
493
|
+
{ enabled: !!props.${queryParams.map((param) => param.name).join(' && !!props.')}, ...options }
|
|
494
|
+
);}
|
|
495
|
+
|
|
496
|
+
use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'>) => {
|
|
497
|
+
const params = queryString.stringify({${queryParams
|
|
498
|
+
.map((param) => `${param.name}: props.${param.name}`)
|
|
499
|
+
.join(',')}});
|
|
500
|
+
const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
|
|
501
|
+
return result.data;
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
|
|
505
|
+
|
|
506
|
+
use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
|
|
507
|
+
|
|
508
|
+
`;
|
|
509
|
+
output += `interface ${componentName}MutationVariables {
|
|
510
|
+
${queryParamsType}
|
|
511
|
+
}
|
|
512
|
+
interface ${componentName}MutationProps<T> {
|
|
513
|
+
options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
|
|
517
|
+
return useMutation(async (data) => {
|
|
518
|
+
const params = queryString.stringify({${queryParams
|
|
519
|
+
.map((param) => `${param.name}: data.${param.name}`)
|
|
520
|
+
.join(',')}});
|
|
521
|
+
const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
|
|
522
|
+
return result.data;
|
|
523
|
+
},
|
|
524
|
+
props?.options
|
|
525
|
+
)};`;
|
|
526
|
+
}
|
|
527
|
+
if (requestBodyComponent && !paramsInPath.length && !queryParam) {
|
|
528
|
+
output += `type ${componentName}QueryVariables = ${requestBodyComponent};
|
|
529
|
+
interface ${componentName}QueryProps<T = ${genericsTypes}> extends ${componentName}QueryVariables {
|
|
530
|
+
options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
|
|
531
|
+
}
|
|
532
|
+
export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...body }: ${componentName}QueryProps<T>) {
|
|
533
|
+
return useQuery(use${componentName}Query.queryKey(body), async () => use${componentName}Query.fetch(body), options
|
|
534
|
+
);}
|
|
535
|
+
|
|
536
|
+
use${componentName}Query.fetch = async (body: Omit<${componentName}QueryProps, 'options'>) => {
|
|
537
|
+
const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
|
|
538
|
+
return result.data
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
|
|
542
|
+
|
|
543
|
+
use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
|
|
544
|
+
|
|
545
|
+
`;
|
|
546
|
+
output += `type ${componentName}MutationVariables = ${requestBodyComponent};
|
|
547
|
+
interface ${componentName}MutationProps<T> {
|
|
548
|
+
options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
|
|
549
|
+
}
|
|
550
|
+
export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
|
|
551
|
+
return useMutation(async (body) => {
|
|
552
|
+
const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
|
|
553
|
+
return result.data
|
|
554
|
+
},
|
|
555
|
+
props?.options
|
|
556
|
+
)};`;
|
|
557
|
+
}
|
|
558
|
+
if (requestBodyComponent && paramsInPath.length && !queryParam) {
|
|
559
|
+
output += `interface ${componentName}QueryProps<T = ${genericsTypes}> extends ${requestBodyComponent
|
|
560
|
+
.replace('{', '')
|
|
561
|
+
.replace('}', '')} {
|
|
562
|
+
${paramsTypes};
|
|
563
|
+
options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
|
|
564
|
+
}
|
|
565
|
+
export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
|
|
566
|
+
return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props), { enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
|
|
567
|
+
);}
|
|
568
|
+
|
|
569
|
+
// HEHEH
|
|
570
|
+
use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'>) => {
|
|
571
|
+
const {${paramsInPath.join(', ')}, ...body} = props
|
|
572
|
+
const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
|
|
573
|
+
return result.data
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
|
|
577
|
+
|
|
578
|
+
use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
`;
|
|
582
|
+
output += `type ${componentName}MutationVariables = {${paramsTypes}} & ${requestBodyComponent}
|
|
583
|
+
interface ${componentName}MutationProps<T> {
|
|
584
|
+
options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
|
|
585
|
+
}
|
|
586
|
+
export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
|
|
587
|
+
return useMutation(async (body) => use${componentName}Query.fetch(body),
|
|
588
|
+
props?.options
|
|
589
|
+
)};`;
|
|
590
|
+
}
|
|
591
|
+
if (requestBodyComponent && queryParam) {
|
|
592
|
+
output += `// TODO: CODEGEN DOES NOT SUPPORT QUERYPARAM AND REQUESTBODY`;
|
|
593
|
+
}
|
|
594
|
+
return output;
|
|
595
|
+
};
|
|
596
|
+
exports.generateRestfulComponent = generateRestfulComponent;
|
|
597
|
+
/**
|
|
598
|
+
* Main entry of the generator. Generate react-query component from openAPI.
|
|
599
|
+
*/
|
|
600
|
+
const importOpenApi = async ({ data, format }) => {
|
|
601
|
+
const operationIds = [];
|
|
602
|
+
let specs = await importSpecs(data, format);
|
|
603
|
+
exports.resolveDiscriminator(specs);
|
|
604
|
+
let output = `
|
|
605
|
+
import { useQuery, useMutation, UseQueryOptions, UseMutationOptions, QueryKey } from 'react-query';
|
|
606
|
+
import queryString from 'query-string';
|
|
607
|
+
import {AxiosError} from 'axios';
|
|
608
|
+
import { api } from 'api';
|
|
609
|
+
`;
|
|
610
|
+
output += '\n\n// SCEHMAS\n';
|
|
611
|
+
output += exports.generateSchemasDefinition(specs.components && specs.components.schemas);
|
|
612
|
+
output += '\n\n// RESPONSES\n';
|
|
613
|
+
output += exports.generateResponsesDefinition(specs.components && specs.components.responses);
|
|
614
|
+
output += '\n\n// REQUEST BODIES\n';
|
|
615
|
+
output += exports.generateRequestBodiesDefinition(specs.components && specs.components.requestBodies);
|
|
616
|
+
output += '\n\n// HOOKS\n';
|
|
617
|
+
Object.entries(specs.paths).forEach(([route, verbs]) => {
|
|
618
|
+
Object.entries(verbs).forEach(([verb, operation]) => {
|
|
619
|
+
if (['get', 'post', 'patch', 'put', 'delete'].includes(verb) && !operation.deprecated) {
|
|
620
|
+
output += exports.generateRestfulComponent(operation, verb, route, operationIds, verbs.parameters, specs.components);
|
|
621
|
+
}
|
|
622
|
+
});
|
|
623
|
+
});
|
|
624
|
+
return output;
|
|
625
|
+
};
|
|
626
|
+
exports.default = importOpenApi;
|
package/lib/cjs/types.js
ADDED
package/lib/esm/index.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import chalk from 'chalk';
|
|
2
|
+
import program from 'commander';
|
|
3
|
+
import { readFileSync, writeFileSync } from 'fs';
|
|
4
|
+
import { join, parse } from 'path';
|
|
5
|
+
import importOpenApi from './scripts/import-open-api';
|
|
6
|
+
const log = console.log; // tslint:disable-line:no-console
|
|
7
|
+
program.option('-o, --output [value]', 'output file destination');
|
|
8
|
+
program.option('-f, --file [value]', 'input file (yaml or json openapi specs)');
|
|
9
|
+
program.parse(process.argv);
|
|
10
|
+
const createSuccessMessage = (backend) => chalk.green(`${backend ? `[${backend}] ` : ''}🎉 Your OpenAPI spec has been converted into react query hooks`);
|
|
11
|
+
const successWithoutOutputMessage = chalk.yellow('Success! No output path specified; printed to standard output.');
|
|
12
|
+
const importSpecs = async (options) => {
|
|
13
|
+
if (!options.file) {
|
|
14
|
+
throw new Error("You need to provide an input specification with `--file`, '--url', or `--github`");
|
|
15
|
+
}
|
|
16
|
+
const data = readFileSync(join(process.cwd(), options.file), 'utf-8');
|
|
17
|
+
const { ext } = parse(options.file);
|
|
18
|
+
const format = ['.yaml', '.yml'].includes(ext.toLowerCase()) ? 'yaml' : 'json';
|
|
19
|
+
return importOpenApi({
|
|
20
|
+
data,
|
|
21
|
+
format,
|
|
22
|
+
});
|
|
23
|
+
};
|
|
24
|
+
// Use flags as configuration
|
|
25
|
+
importSpecs(program)
|
|
26
|
+
.then((data) => {
|
|
27
|
+
if (program.output) {
|
|
28
|
+
writeFileSync(join(process.cwd(), program.output), data);
|
|
29
|
+
log(createSuccessMessage());
|
|
30
|
+
}
|
|
31
|
+
else {
|
|
32
|
+
log(data);
|
|
33
|
+
log(successWithoutOutputMessage);
|
|
34
|
+
}
|
|
35
|
+
})
|
|
36
|
+
.catch((err) => {
|
|
37
|
+
log(chalk.red(err));
|
|
38
|
+
process.exit(1);
|
|
39
|
+
});
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import program from 'commander';
|
|
2
|
+
import { readFileSync } from 'fs';
|
|
3
|
+
import { join } from 'path';
|
|
4
|
+
const { version } = JSON.parse(readFileSync(join(__dirname, '../../package.json'), 'utf-8'));
|
|
5
|
+
export const codegen = () => {
|
|
6
|
+
program
|
|
7
|
+
.version(version)
|
|
8
|
+
.command('import [open-api-file]', 'generate react-query hooks from OpenAPI specs')
|
|
9
|
+
.parse(process.argv);
|
|
10
|
+
};
|