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.
@@ -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
+ if (!operation.operationId) {
297
+ throw new Error(`Every path must have a operationId - No operationId set for ${verb} ${route}`);
298
+ }
299
+ if (operationIds.includes(operation.operationId)) {
300
+ throw new Error(`"${operation.operationId}" is duplicated in your schema definition!`);
301
+ }
302
+ operationIds.push(operation.operationId);
303
+ route = route.replace(/\{/g, '${'); // `/pet/{id}` => `/pet/${id}`
304
+ // Remove the last param of the route if we are in the DELETE case
305
+ let lastParamInTheRoute = null;
306
+ const componentName = pascal(operation.operationId);
307
+ const isOk = ([statusCode]) => statusCode.toString().startsWith('2');
308
+ const responseTypes = getResReqTypes(Object.entries(operation.responses).filter(isOk)) || 'void';
309
+ const requestBodyTypes = getResReqTypes([['body', operation.requestBody]]);
310
+ const needAResponseComponent = true;
311
+ const paramsInPath = getParamsInPath(route).filter((param) => !(verb === 'delete' && param === lastParamInTheRoute));
312
+ const { query: queryParams = [], path: pathParams = [] } = groupBy([...parameters, ...(operation.parameters || [])].map((p) => {
313
+ if (isReference(p)) {
314
+ return get(schemasComponents, p.$ref.replace('#/components/', '').replace('/', '.'));
315
+ }
316
+ else {
317
+ return p;
318
+ }
319
+ }), 'in');
320
+ const paramsTypes = paramsInPath
321
+ .map((p) => {
322
+ try {
323
+ const { name, required, schema } = pathParams.find((i) => i.name === p);
324
+ return `${name}${required ? '' : '?'}: ${resolveValue(schema)}`;
325
+ }
326
+ catch (err) {
327
+ throw new Error(`The path params ${p} can't be found in parameters (${operation.operationId})`);
328
+ }
329
+ })
330
+ .join('; ');
331
+ const queryParamsType = queryParams
332
+ .map((p) => {
333
+ const processedName = IdentifierRegexp.test(p.name) ? p.name : `"${p.name}"`;
334
+ return `${formatDescription(p.description, 2)}${processedName}${p.required ? '' : '?'}: ${resolveValue(p.schema)}`;
335
+ })
336
+ .join(';\n ');
337
+ // Retrieve the type of the param for delete verb
338
+ const lastParamInTheRouteDefinition = operation.parameters && lastParamInTheRoute
339
+ ? operation.parameters.find((p) => {
340
+ if (isReference(p)) {
341
+ return false;
342
+ }
343
+ return p.name === lastParamInTheRoute;
344
+ }) // Reference is not possible
345
+ : { schema: { type: 'string' } };
346
+ if (!lastParamInTheRouteDefinition) {
347
+ throw new Error(`The path params ${lastParamInTheRoute} can't be found in parameters (${operation.operationId})`);
348
+ }
349
+ let genericsTypes = `${needAResponseComponent ? componentName + 'Res' : responseTypes}`;
350
+ if (verb !== 'get') {
351
+ genericsTypes = `${needAResponseComponent ? componentName + 'Res' : responseTypes}`;
352
+ }
353
+ const description = formatDescription(operation.summary && operation.description
354
+ ? `${operation.summary}\n\n${operation.description}`
355
+ : `${operation.summary || ''}${operation.description || ''}`);
356
+ let output = `\n\n${description}`;
357
+ const typeOrInterface = `type ${componentName}Res =`;
358
+ output += `
359
+ ${needAResponseComponent ? `export ${typeOrInterface} ${responseTypes}` : ''}
360
+ `;
361
+ const queryParam = queryParamsType && queryParamsType !== 'void' ? `${queryParamsType}` : '';
362
+ const requestBodyComponent = requestBodyTypes && requestBodyTypes !== 'void' ? `${requestBodyTypes}` : '';
363
+ // QUERIES
364
+ if (!requestBodyComponent && paramsInPath.length && !queryParam) {
365
+ output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
366
+ ${paramsTypes};
367
+ options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
368
+ }
369
+ export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
370
+ return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
371
+ { enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
372
+ );}
373
+
374
+ use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'> ) => {
375
+ const result = await api.${verb}<${genericsTypes}>(\`${route.replace(/\{/g, '{props.')}\`);
376
+ return result.data;
377
+ }
378
+
379
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
380
+
381
+ use${componentName}Query.queryKey = (params: {${paramsTypes}} ): QueryKey => [...use${componentName}Query.baseKey(), params];
382
+
383
+ `;
384
+ output += `interface ${componentName}MutationVariables {
385
+ ${paramsTypes}
386
+ }
387
+ interface ${componentName}MutationProps<T> {
388
+ options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
389
+ }
390
+ export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
391
+ return useMutation(async ({${paramsInPath.join(', ')}}) => {
392
+ const result = await api.${verb}<${genericsTypes}>(\`${route}\`)
393
+ return result.data
394
+ },
395
+ props?.options
396
+ )};`;
397
+ }
398
+ if (!requestBodyComponent && paramsInPath.length && queryParam) {
399
+ output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
400
+ ${paramsTypes};
401
+ ${queryParamsType};
402
+ options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
403
+ }
404
+ export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
405
+ return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props), { enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
406
+ );}
407
+
408
+ use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'>) => {
409
+ const {${paramsInPath.join(', ')}, ...queryParams} = props
410
+ const params = queryString.stringify(queryParams);
411
+ const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
412
+ return result.data;
413
+ }
414
+
415
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
416
+
417
+ use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'>): QueryKey => [...use${componentName}Query.baseKey(), params];
418
+
419
+ `;
420
+ output += `interface ${componentName}MutationVariables {
421
+ ${paramsTypes}
422
+ ${queryParamsType}
423
+ }
424
+ interface ${componentName}MutationProps<T> {
425
+ options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
426
+ }
427
+ export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
428
+ return useMutation(async (data) => {
429
+ const {${paramsInPath.join(', ')}, ...queryParams} = data
430
+ const params = queryString.stringify(queryParams);
431
+ const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
432
+ return result.data
433
+ },
434
+ props?.options
435
+ )};`;
436
+ }
437
+ if (!requestBodyComponent && !paramsInPath.length && !queryParam) {
438
+ output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
439
+ options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
440
+ }
441
+ export function use${componentName}Query<T = ${genericsTypes}>(props?: ${componentName}QueryProps<T>) {
442
+ return useQuery(use${componentName}Query.queryKey(), use${componentName}Query.fetch, props?.options
443
+ );}
444
+
445
+ use${componentName}Query.fetch = async () => {
446
+ const result = await api.${verb}<${genericsTypes}>(\`${route}\`);
447
+ return result.data;
448
+ }
449
+
450
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
451
+
452
+ use${componentName}Query.queryKey = (): QueryKey => use${componentName}Query.baseKey()
453
+
454
+ `;
455
+ output += `interface ${componentName}MutationProps<T> {
456
+ options?: UseMutationOptions<${genericsTypes}, AxiosError, void, T>
457
+ }
458
+ export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
459
+ return useMutation(async () => {
460
+ const result = await api.${verb}<${genericsTypes}>(\`${route}\`);
461
+ return result.data;
462
+ },
463
+ props?.options
464
+ )};`;
465
+ }
466
+ if (!requestBodyComponent && !paramsInPath.length && queryParam) {
467
+ output += `interface ${componentName}QueryProps<T = ${genericsTypes}> {
468
+ ${queryParamsType};
469
+ options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
470
+ }
471
+ export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
472
+ return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
473
+ { enabled: !!props.${queryParams.map((param) => param.name).join(' && !!props.')}, ...options }
474
+ );}
475
+
476
+ use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'>) => {
477
+ const params = queryString.stringify({${queryParams
478
+ .map((param) => `${param.name}: props.${param.name}`)
479
+ .join(',')}});
480
+ const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
481
+ return result.data;
482
+ }
483
+
484
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
485
+
486
+ use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
487
+
488
+ `;
489
+ output += `interface ${componentName}MutationVariables {
490
+ ${queryParamsType}
491
+ }
492
+ interface ${componentName}MutationProps<T> {
493
+ options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
494
+ }
495
+
496
+ export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
497
+ return useMutation(async (data) => {
498
+ const params = queryString.stringify({${queryParams
499
+ .map((param) => `${param.name}: data.${param.name}`)
500
+ .join(',')}});
501
+ const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
502
+ return result.data;
503
+ },
504
+ props?.options
505
+ )};`;
506
+ }
507
+ if (requestBodyComponent && !paramsInPath.length && !queryParam) {
508
+ output += `type ${componentName}QueryVariables = ${requestBodyComponent};
509
+ interface ${componentName}QueryProps<T = ${genericsTypes}> extends ${componentName}QueryVariables {
510
+ options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
511
+ }
512
+ export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...body }: ${componentName}QueryProps<T>) {
513
+ return useQuery(use${componentName}Query.queryKey(body), async () => use${componentName}Query.fetch(body), options
514
+ );}
515
+
516
+ use${componentName}Query.fetch = async (body: Omit<${componentName}QueryProps, 'options'>) => {
517
+ const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
518
+ return result.data
519
+ }
520
+
521
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
522
+
523
+ use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
524
+
525
+ `;
526
+ output += `type ${componentName}MutationVariables = ${requestBodyComponent};
527
+ interface ${componentName}MutationProps<T> {
528
+ options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
529
+ }
530
+ export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
531
+ return useMutation(async (body) => {
532
+ const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
533
+ return result.data
534
+ },
535
+ props?.options
536
+ )};`;
537
+ }
538
+ if (requestBodyComponent && paramsInPath.length && !queryParam) {
539
+ output += `interface ${componentName}QueryProps<T = ${genericsTypes}> extends ${requestBodyComponent
540
+ .replace('{', '')
541
+ .replace('}', '')} {
542
+ ${paramsTypes};
543
+ options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
544
+ }
545
+ export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
546
+ return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props), { enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
547
+ );}
548
+
549
+ // HEHEH
550
+ use${componentName}Query.fetch = async (props: Omit<${componentName}QueryProps, 'options'>) => {
551
+ const {${paramsInPath.join(', ')}, ...body} = props
552
+ const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
553
+ return result.data
554
+ }
555
+
556
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
557
+
558
+ use${componentName}Query.queryKey = (params: Omit<${componentName}QueryProps, 'options'> ): QueryKey => [...use${componentName}Query.baseKey(), params];
559
+
560
+
561
+ `;
562
+ output += `type ${componentName}MutationVariables = {${paramsTypes}} & ${requestBodyComponent}
563
+ interface ${componentName}MutationProps<T> {
564
+ options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}MutationVariables, T>
565
+ }
566
+ export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
567
+ return useMutation(async (body) => use${componentName}Query.fetch(body),
568
+ props?.options
569
+ )};`;
570
+ }
571
+ if (requestBodyComponent && queryParam) {
572
+ output += `// TODO: CODEGEN DOES NOT SUPPORT QUERYPARAM AND REQUESTBODY`;
573
+ }
574
+ return output;
575
+ };
576
+ /**
577
+ * Main entry of the generator. Generate react-query component from openAPI.
578
+ */
579
+ const importOpenApi = async ({ data, format }) => {
580
+ const operationIds = [];
581
+ let specs = await importSpecs(data, format);
582
+ resolveDiscriminator(specs);
583
+ let output = `
584
+ import { useQuery, useMutation, UseQueryOptions, UseMutationOptions, QueryKey } from 'react-query';
585
+ import queryString from 'query-string';
586
+ import {AxiosError} from 'axios';
587
+ import { api } from 'api';
588
+ `;
589
+ output += '\n\n// SCEHMAS\n';
590
+ output += generateSchemasDefinition(specs.components && specs.components.schemas);
591
+ output += '\n\n// RESPONSES\n';
592
+ output += generateResponsesDefinition(specs.components && specs.components.responses);
593
+ output += '\n\n// REQUEST BODIES\n';
594
+ output += generateRequestBodiesDefinition(specs.components && specs.components.requestBodies);
595
+ output += '\n\n// HOOKS\n';
596
+ Object.entries(specs.paths).forEach(([route, verbs]) => {
597
+ Object.entries(verbs).forEach(([verb, operation]) => {
598
+ if (['get', 'post', 'patch', 'put', 'delete'].includes(verb) && !operation.deprecated) {
599
+ output += generateRestfulComponent(operation, verb, route, operationIds, verbs.parameters, specs.components);
600
+ }
601
+ });
602
+ });
603
+ return output;
604
+ };
605
+ export default importOpenApi;
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,9 +1,14 @@
1
1
  {
2
2
  "name": "react-query-lightbase-codegen",
3
- "version": "0.0.2",
3
+ "version": "0.0.3",
4
4
  "license": "MIT",
5
- "main": "./dist/index.js",
5
+ "main": "./lib/cjs/index.js",
6
+ "module": "./lib/esm/index.js",
7
+ "files": [
8
+ "lib/"
9
+ ],
6
10
  "scripts": {
11
+ "tsc": "tsc -p tsconfig.json && tsc -p tsconfig-cjs.json",
7
12
  "build": "run-p build:*",
8
13
  "build:project": "tsdx build",
9
14
  "build:bin": "tsc && rollup -c rollup.config.js",
package/.eslintrc.js DELETED
@@ -1,7 +0,0 @@
1
- module.exports = {
2
- root: true,
3
- extends: '@lightbase/eslint-config-lightbase/rn',
4
- env: {
5
- jest: true,
6
- },
7
- };
package/.prettierrc DELETED
@@ -1,8 +0,0 @@
1
- {
2
- "printWidth": 110,
3
- "tabWidth": 2,
4
- "singleQuote": true,
5
- "jsxBracketSameLine": false,
6
- "trailingComma": "es5",
7
- "arrowParens": "always"
8
- }
package/rollup.config.js DELETED
@@ -1,15 +0,0 @@
1
- const { readdirSync } = require('fs');
2
-
3
- /**
4
- * Rollup configuration to build correctly our scripts (nodejs scripts need to be cjs)
5
- */
6
- module.exports = readdirSync('lib')
7
- .filter((file) => file.endsWith('.js'))
8
- .map((file) => ({
9
- input: `lib/${file}`,
10
- output: {
11
- file: `dist/${file}`,
12
- format: 'cjs',
13
- banner: '#!/usr/bin/env node',
14
- },
15
- }));