react-query-lightbase-codegen 0.0.2 → 0.0.5

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.
@@ -0,0 +1,627 @@
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.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 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
+ const { operationId = route.replace('/', '') } = operation;
317
+ if (operationId === '*') {
318
+ throw new Error(`Invalid operationId/Route set for ${verb} ${route}`);
319
+ }
320
+ if (operationIds.includes(operationId)) {
321
+ throw new Error(`"${operationId}" is duplicated in your schema definition!`);
322
+ }
323
+ operationIds.push(operationId);
324
+ route = route.replace(/\{/g, '${'); // `/pet/{id}` => `/pet/${id}`
325
+ // Remove the last param of the route if we are in the DELETE case
326
+ let lastParamInTheRoute = null;
327
+ const componentName = case_1.pascal(operationId);
328
+ 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]]);
331
+ const needAResponseComponent = true;
332
+ const paramsInPath = exports.getParamsInPath(route).filter((param) => !(verb === 'delete' && param === lastParamInTheRoute));
333
+ const { query: queryParams = [], path: pathParams = [] } = groupBy_1.default([...parameters, ...(operation.parameters || [])].map((p) => {
334
+ if (exports.isReference(p)) {
335
+ return get_1.default(schemasComponents, p.$ref.replace('#/components/', '').replace('/', '.'));
336
+ }
337
+ else {
338
+ return p;
339
+ }
340
+ }), 'in');
341
+ const paramsTypes = paramsInPath
342
+ .map((p) => {
343
+ try {
344
+ const { name, required, schema } = pathParams.find((i) => i.name === p);
345
+ return `${name}${required ? '' : '?'}: ${exports.resolveValue(schema)}`;
346
+ }
347
+ catch (err) {
348
+ throw new Error(`The path params ${p} can't be found in parameters (${operationId})`);
349
+ }
350
+ })
351
+ .join('; ');
352
+ const queryParamsType = queryParams
353
+ .map((p) => {
354
+ const processedName = IdentifierRegexp.test(p.name) ? p.name : `"${p.name}"`;
355
+ return `${exports.formatDescription(p.description, 2)}${processedName}${p.required ? '' : '?'}: ${exports.resolveValue(p.schema)}`;
356
+ })
357
+ .join(';\n ');
358
+ // Retrieve the type of the param for delete verb
359
+ const lastParamInTheRouteDefinition = operation.parameters && lastParamInTheRoute
360
+ ? operation.parameters.find((p) => {
361
+ if (exports.isReference(p)) {
362
+ return false;
363
+ }
364
+ return p.name === lastParamInTheRoute;
365
+ }) // Reference is not possible
366
+ : { schema: { type: 'string' } };
367
+ if (!lastParamInTheRouteDefinition) {
368
+ throw new Error(`The path params ${lastParamInTheRoute} can't be found in parameters (${operationId})`);
369
+ }
370
+ let genericsTypes = `${needAResponseComponent ? componentName + 'Res' : responseTypes}`;
371
+ if (verb !== 'get') {
372
+ genericsTypes = `${needAResponseComponent ? componentName + 'Res' : responseTypes}`;
373
+ }
374
+ const description = exports.formatDescription(operation.summary && operation.description
375
+ ? `${operation.summary}\n\n${operation.description}`
376
+ : `${operation.summary || ''}${operation.description || ''}`);
377
+ let output = `\n\n${description}`;
378
+ const typeOrInterface = `type ${componentName}Res =`;
379
+ output += `
380
+ ${needAResponseComponent ? `export ${typeOrInterface} ${responseTypes}` : ''}
381
+ `;
382
+ const queryParam = queryParamsType && queryParamsType !== 'void' ? `${queryParamsType}` : '';
383
+ const requestBodyComponent = requestBodyTypes && requestBodyTypes !== 'void' ? `${requestBodyTypes}` : '';
384
+ // QUERIES
385
+ if (!requestBodyComponent && paramsInPath.length && !queryParam) {
386
+ output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
387
+ ${paramsTypes};
388
+ options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
389
+ }
390
+ export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
391
+ return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
392
+ { enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
393
+ );}
394
+
395
+ use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'> ) => {
396
+ const result = await api.${verb}<${genericsTypes}>(\`${route.replace(/\{/g, '{props.')}\`);
397
+ return result.data;
398
+ }
399
+
400
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
401
+
402
+ use${componentName}Query.queryKey = (params: {${paramsTypes}} ): QueryKey => [...use${componentName}Query.baseKey(), params];
403
+
404
+ `;
405
+ output += `interface ${componentName}MutationVariables {
406
+ ${paramsTypes}
407
+ }
408
+ interface ${componentName}MutationProps<T> {
409
+ options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
410
+ }
411
+ export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
412
+ return useMutation(async ({${paramsInPath.join(', ')}}) => {
413
+ const result = await api.${verb}<${genericsTypes}>(\`${route}\`)
414
+ return result.data
415
+ },
416
+ props?.options
417
+ )};`;
418
+ }
419
+ if (!requestBodyComponent && paramsInPath.length && queryParam) {
420
+ output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
421
+ ${paramsTypes};
422
+ ${queryParamsType};
423
+ options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
424
+ }
425
+ export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
426
+ return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props), { enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
427
+ );}
428
+
429
+ use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'>) => {
430
+ const {${paramsInPath.join(', ')}, ...queryParams} = props
431
+ const params = queryString.stringify(queryParams);
432
+ const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
433
+ return result.data;
434
+ }
435
+
436
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
437
+
438
+ use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'>): QueryKey => [...use${componentName}Query.baseKey(), params];
439
+
440
+ `;
441
+ output += `interface ${componentName}MutationVariables {
442
+ ${paramsTypes}
443
+ ${queryParamsType}
444
+ }
445
+ interface ${componentName}MutationProps<T> {
446
+ options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
447
+ }
448
+ export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
449
+ return useMutation(async (data) => {
450
+ const {${paramsInPath.join(', ')}, ...queryParams} = data
451
+ const params = queryString.stringify(queryParams);
452
+ const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
453
+ return result.data
454
+ },
455
+ props?.options
456
+ )};`;
457
+ }
458
+ if (!requestBodyComponent && !paramsInPath.length && !queryParam) {
459
+ output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
460
+ options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
461
+ }
462
+ export function use${componentName}Query<T = ${genericsTypes}>(props?: ${componentName}QueryProps<T>) {
463
+ return useQuery(use${componentName}Query.queryKey(), use${componentName}Query.fetch, props?.options
464
+ );}
465
+
466
+ use${componentName}Query.fetch = async () => {
467
+ const result = await api.${verb}<${genericsTypes}>(\`${route}\`);
468
+ return result.data;
469
+ }
470
+
471
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
472
+
473
+ use${componentName}Query.queryKey = (): QueryKey => use${componentName}Query.baseKey()
474
+
475
+ `;
476
+ output += `interface ${componentName}MutationProps<T> {
477
+ options?: UseMutationOptions<${genericsTypes}, AxiosError, void, T>
478
+ }
479
+ export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
480
+ return useMutation(async () => {
481
+ const result = await api.${verb}<${genericsTypes}>(\`${route}\`);
482
+ return result.data;
483
+ },
484
+ props?.options
485
+ )};`;
486
+ }
487
+ if (!requestBodyComponent && !paramsInPath.length && queryParam) {
488
+ output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
489
+ ${queryParamsType};
490
+ options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
491
+ }
492
+ export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
493
+ return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
494
+ { enabled: !!props.${queryParams.map((param) => param.name).join(' && !!props.')}, ...options }
495
+ );}
496
+
497
+ use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'>) => {
498
+ const params = queryString.stringify({${queryParams
499
+ .map((param) => `${param.name}: props.${param.name}`)
500
+ .join(',')}});
501
+ const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
502
+ return result.data;
503
+ }
504
+
505
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
506
+
507
+ use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
508
+
509
+ `;
510
+ output += `interface ${componentName}MutationVariables {
511
+ ${queryParamsType}
512
+ }
513
+ interface ${componentName}MutationProps<T> {
514
+ options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
515
+ }
516
+
517
+ export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
518
+ return useMutation(async (data) => {
519
+ const params = queryString.stringify({${queryParams
520
+ .map((param) => `${param.name}: data.${param.name}`)
521
+ .join(',')}});
522
+ const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
523
+ return result.data;
524
+ },
525
+ props?.options
526
+ )};`;
527
+ }
528
+ if (requestBodyComponent && !paramsInPath.length && !queryParam) {
529
+ output += `type ${componentName}QueryVariables = ${requestBodyComponent};
530
+ interface ${componentName}QueryProps<T = ${genericsTypes}> extends ${componentName}QueryVariables {
531
+ options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
532
+ }
533
+ export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...body }: ${componentName}QueryProps<T>) {
534
+ return useQuery(use${componentName}Query.queryKey(body), async () => use${componentName}Query.fetch(body), options
535
+ );}
536
+
537
+ use${componentName}Query.fetch = async (body: Omit<${componentName}QueryProps, 'options'>) => {
538
+ const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
539
+ return result.data
540
+ }
541
+
542
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
543
+
544
+ use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
545
+
546
+ `;
547
+ output += `type ${componentName}MutationVariables = ${requestBodyComponent};
548
+ interface ${componentName}MutationProps<T> {
549
+ options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
550
+ }
551
+ export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
552
+ return useMutation(async (body) => {
553
+ const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
554
+ return result.data
555
+ },
556
+ props?.options
557
+ )};`;
558
+ }
559
+ if (requestBodyComponent && paramsInPath.length && !queryParam) {
560
+ output += `interface ${componentName}QueryProps<T = ${genericsTypes}> extends ${requestBodyComponent
561
+ .replace('{', '')
562
+ .replace('}', '')} {
563
+ ${paramsTypes};
564
+ options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
565
+ }
566
+ export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
567
+ return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props), { enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
568
+ );}
569
+
570
+ // HEHEH
571
+ use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'>) => {
572
+ const {${paramsInPath.join(', ')}, ...body} = props
573
+ const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
574
+ return result.data
575
+ }
576
+
577
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
578
+
579
+ use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
580
+
581
+
582
+ `;
583
+ output += `type ${componentName}MutationVariables = {${paramsTypes}} & ${requestBodyComponent}
584
+ interface ${componentName}MutationProps<T> {
585
+ options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
586
+ }
587
+ export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
588
+ return useMutation(async (body) => use${componentName}Query.fetch(body),
589
+ props?.options
590
+ )};`;
591
+ }
592
+ if (requestBodyComponent && queryParam) {
593
+ output += `// TODO: CODEGEN DOES NOT SUPPORT QUERYPARAM AND REQUESTBODY`;
594
+ }
595
+ return output;
596
+ };
597
+ exports.generateRestfulComponent = generateRestfulComponent;
598
+ /**
599
+ * Main entry of the generator. Generate react-query component from openAPI.
600
+ */
601
+ const importOpenApi = async ({ data, format }) => {
602
+ const operationIds = [];
603
+ let specs = await importSpecs(data, format);
604
+ exports.resolveDiscriminator(specs);
605
+ let output = `
606
+ import { useQuery, useMutation, UseQueryOptions, UseMutationOptions, QueryKey } from 'react-query';
607
+ import queryString from 'query-string';
608
+ import {AxiosError} from 'axios';
609
+ import { api } from 'api';
610
+ `;
611
+ output += '\n\n// SCEHMAS\n';
612
+ output += exports.generateSchemasDefinition(specs.components && specs.components.schemas);
613
+ output += '\n\n// RESPONSES\n';
614
+ output += exports.generateResponsesDefinition(specs.components && specs.components.responses);
615
+ output += '\n\n// REQUEST BODIES\n';
616
+ output += exports.generateRequestBodiesDefinition(specs.components && specs.components.requestBodies);
617
+ output += '\n\n// HOOKS\n';
618
+ Object.entries(specs.paths).forEach(([route, verbs]) => {
619
+ Object.entries(verbs).forEach(([verb, operation]) => {
620
+ if (['get', 'post', 'patch', 'put', 'delete'].includes(verb) && !operation.deprecated) {
621
+ output += exports.generateRestfulComponent(operation, verb, route, operationIds, verbs.parameters, specs.components);
622
+ }
623
+ });
624
+ });
625
+ return output;
626
+ };
627
+ exports.importOpenApi = importOpenApi;
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.importSpecs = void 0;
4
+ const react_query_codegen_import_1 = require("./react-query-codegen-import");
5
+ Object.defineProperty(exports, "importSpecs", { enumerable: true, get: function () { return react_query_codegen_import_1.importSpecs; } });
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.importSpecs = void 0;
7
+ const chalk_1 = __importDefault(require("chalk"));
8
+ const fs_1 = require("fs");
9
+ const path_1 = require("path");
10
+ const import_open_api_1 = require("./import-open-api");
11
+ const log = console.log; // tslint:disable-line:no-console
12
+ const createSuccessMessage = (backend) => chalk_1.default.green(`🎉 ${backend ? `[${backend}] ` : ''} Your OpenAPI spec has been converted into react query hooks`);
13
+ function importSpecs(dirname, exportDirName) {
14
+ fs_1.readdir(dirname, function (err, filenames) {
15
+ if (err) {
16
+ throw err;
17
+ }
18
+ filenames.map(async (filename) => {
19
+ const data = fs_1.readFileSync(path_1.join(process.cwd(), dirname + '/' + filename), 'utf-8');
20
+ const { ext } = path_1.parse(dirname + '/' + filename);
21
+ const format = ['.yaml', '.yml'].includes(ext.toLowerCase()) ? 'yaml' : 'json';
22
+ try {
23
+ const name = `useQueries${filename.split('.')[0]}.tsx`;
24
+ const fileExports = await import_open_api_1.importOpenApi({ data, format });
25
+ fs_1.writeFileSync(path_1.join(process.cwd(), `${exportDirName}/${name}`), fileExports);
26
+ log(createSuccessMessage(filename));
27
+ }
28
+ catch (error) {
29
+ log(chalk_1.default.red(`[${filename}]:`), chalk_1.default.red(error));
30
+ // process.exit(1);
31
+ }
32
+ });
33
+ });
34
+ }
35
+ exports.importSpecs = importSpecs;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });