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