react-query-lightbase-codegen 0.1.7 → 0.1.10

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.
@@ -140,7 +140,7 @@ const getObject = (item) => {
140
140
  if (item.properties) {
141
141
  output += '\n';
142
142
  }
143
- output += ` [key: string]: ${item.additionalProperties === true ? 'any' : (0, exports.resolveValue)(item.additionalProperties)};`;
143
+ output += `} & { [key: string]: ${item.additionalProperties === true ? 'any' : (0, exports.resolveValue)(item.additionalProperties)}`;
144
144
  }
145
145
  if (item.properties || item.additionalProperties) {
146
146
  if (output === '{\n') {
@@ -205,7 +205,7 @@ const generateInterface = (name, schema) => {
205
205
  const scalar = (0, exports.getScalar)(schema);
206
206
  return `
207
207
  ${(0, exports.formatDescription)(schema.description)}
208
- export interface ${(0, case_1.pascal)(name)} ${scalar}
208
+ export type ${(0, case_1.pascal)(name)} = ${scalar}
209
209
  `;
210
210
  };
211
211
  exports.generateInterface = generateInterface;
@@ -264,10 +264,10 @@ const generateRequestBodiesDefinition = (requestBodies = {}) => {
264
264
  const type = (0, exports.getResReqTypes)([['', requestBody]]);
265
265
  const isEmptyInterface = type === '{}';
266
266
  if (isEmptyInterface) {
267
- return `export interface ${(0, case_1.pascal)(name)}RequestBody ${type}`;
267
+ return `export type ${(0, case_1.pascal)(name)}RequestBody = ${type}`;
268
268
  }
269
269
  else if (type.includes('{') && !type.includes('|') && !type.includes('&')) {
270
- return `${doc}export interface ${(0, case_1.pascal)(name)}RequestBody ${type}`;
270
+ return `${doc}export type ${(0, case_1.pascal)(name)}RequestBody = ${type}`;
271
271
  }
272
272
  else {
273
273
  return `${doc}export type ${(0, case_1.pascal)(name)}RequestBody = ${type};`;
@@ -291,10 +291,10 @@ const generateResponsesDefinition = (responses = {}) => {
291
291
  const type = (0, exports.getResReqTypes)([['', response]]);
292
292
  const isEmptyInterface = type === '{}';
293
293
  if (isEmptyInterface) {
294
- return `export interface RQ${(0, case_1.pascal)(name)}Response ${type}`;
294
+ return `export type RQ${(0, case_1.pascal)(name)}Response = ${type}`;
295
295
  }
296
296
  else if (type.includes('{') && !type.includes('|') && !type.includes('&')) {
297
- return `${doc}export interface RQ${(0, case_1.pascal)(name)}Response ${type}`;
297
+ return `${doc}export type RQ${(0, case_1.pascal)(name)}Response = ${type}`;
298
298
  }
299
299
  else {
300
300
  return `${doc}export type RQ${(0, case_1.pascal)(name)}Response = ${type};`;
@@ -345,12 +345,19 @@ const generateRestfulComponent = ({ operation, verb, route, operationIds, parame
345
345
  }), 'in');
346
346
  const headerParams = header.filter((p) => !headerFilters?.includes(p.name));
347
347
  let enabled = [];
348
+ let enabledParam = '!!props';
348
349
  [...queryParams, ...pathParams, ...headerParams].forEach((item) => {
349
350
  if (item.required) {
350
351
  enabled.push(`["${item.name}"]`);
352
+ if (enabledParam) {
353
+ enabledParam += `&& props['${item.name}'] != null`;
354
+ }
355
+ else {
356
+ enabledParam = `props['${item.name}'] != null`;
357
+ }
351
358
  }
352
359
  });
353
- const enabledParam = `!!props${enabled.join(' && !!props')}`;
360
+ // `!props${enabled.join('== null && !props')}`;
354
361
  const paramsTypes = paramsInPath
355
362
  .map((p) => {
356
363
  try {
@@ -904,8 +911,8 @@ const generateRestfulComponent = ({ operation, verb, route, operationIds, parame
904
911
  type ${componentName}QueryProps<T = ${componentName}Return> = ${componentName}Variables & {
905
912
  options?: UseQueryOptions<${componentName}Return, AxiosError, T, any>
906
913
  }
907
- export function use${componentName}Query<T = ${componentName}Return>({ options = {}, ...body }: ${componentName}QueryProps<T>) {
908
- return useQuery(use${componentName}Query.queryKey(body), async () => use${componentName}Query.fetch(body),
914
+ export function use${componentName}Query<T = ${componentName}Return>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
915
+ return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
909
916
  { enabled: ${enabledParam}, ...options }
910
917
  );}
911
918
 
@@ -960,9 +967,8 @@ const importOpenApi = async ({ data, format, apiDirectory, queryClientDir, heade
960
967
  UseMutationOptions,
961
968
  QueryKey,
962
969
  SetDataOptions,
963
- QueryFilters
964
970
  } from 'react-query';
965
- import { Updater } from 'react-query/types/core/utils';
971
+ import { Updater, QueryFilters } from 'react-query/types/core/utils';
966
972
 
967
973
  import queryString from 'query-string';
968
974
  import { AxiosError } from 'axios';
@@ -130,7 +130,7 @@ export const getObject = (item) => {
130
130
  if (item.properties) {
131
131
  output += '\n';
132
132
  }
133
- output += ` [key: string]: ${item.additionalProperties === true ? 'any' : resolveValue(item.additionalProperties)};`;
133
+ output += `} & { [key: string]: ${item.additionalProperties === true ? 'any' : resolveValue(item.additionalProperties)}`;
134
134
  }
135
135
  if (item.properties || item.additionalProperties) {
136
136
  if (output === '{\n') {
@@ -191,7 +191,7 @@ export const generateInterface = (name, schema) => {
191
191
  const scalar = getScalar(schema);
192
192
  return `
193
193
  ${formatDescription(schema.description)}
194
- export interface ${pascal(name)} ${scalar}
194
+ export type ${pascal(name)} = ${scalar}
195
195
  `;
196
196
  };
197
197
  /**
@@ -247,10 +247,10 @@ export const generateRequestBodiesDefinition = (requestBodies = {}) => {
247
247
  const type = getResReqTypes([['', requestBody]]);
248
248
  const isEmptyInterface = type === '{}';
249
249
  if (isEmptyInterface) {
250
- return `export interface ${pascal(name)}RequestBody ${type}`;
250
+ return `export type ${pascal(name)}RequestBody = ${type}`;
251
251
  }
252
252
  else if (type.includes('{') && !type.includes('|') && !type.includes('&')) {
253
- return `${doc}export interface ${pascal(name)}RequestBody ${type}`;
253
+ return `${doc}export type ${pascal(name)}RequestBody = ${type}`;
254
254
  }
255
255
  else {
256
256
  return `${doc}export type ${pascal(name)}RequestBody = ${type};`;
@@ -273,10 +273,10 @@ export const generateResponsesDefinition = (responses = {}) => {
273
273
  const type = getResReqTypes([['', response]]);
274
274
  const isEmptyInterface = type === '{}';
275
275
  if (isEmptyInterface) {
276
- return `export interface RQ${pascal(name)}Response ${type}`;
276
+ return `export type RQ${pascal(name)}Response = ${type}`;
277
277
  }
278
278
  else if (type.includes('{') && !type.includes('|') && !type.includes('&')) {
279
- return `${doc}export interface RQ${pascal(name)}Response ${type}`;
279
+ return `${doc}export type RQ${pascal(name)}Response = ${type}`;
280
280
  }
281
281
  else {
282
282
  return `${doc}export type RQ${pascal(name)}Response = ${type};`;
@@ -325,12 +325,19 @@ export const generateRestfulComponent = ({ operation, verb, route, operationIds,
325
325
  }), 'in');
326
326
  const headerParams = header.filter((p) => !headerFilters?.includes(p.name));
327
327
  let enabled = [];
328
+ let enabledParam = '!!props';
328
329
  [...queryParams, ...pathParams, ...headerParams].forEach((item) => {
329
330
  if (item.required) {
330
331
  enabled.push(`["${item.name}"]`);
332
+ if (enabledParam) {
333
+ enabledParam += `&& props['${item.name}'] != null`;
334
+ }
335
+ else {
336
+ enabledParam = `props['${item.name}'] != null`;
337
+ }
331
338
  }
332
339
  });
333
- const enabledParam = `!!props${enabled.join(' && !!props')}`;
340
+ // `!props${enabled.join('== null && !props')}`;
334
341
  const paramsTypes = paramsInPath
335
342
  .map((p) => {
336
343
  try {
@@ -884,8 +891,8 @@ export const generateRestfulComponent = ({ operation, verb, route, operationIds,
884
891
  type ${componentName}QueryProps<T = ${componentName}Return> = ${componentName}Variables & {
885
892
  options?: UseQueryOptions<${componentName}Return, AxiosError, T, any>
886
893
  }
887
- export function use${componentName}Query<T = ${componentName}Return>({ options = {}, ...body }: ${componentName}QueryProps<T>) {
888
- return useQuery(use${componentName}Query.queryKey(body), async () => use${componentName}Query.fetch(body),
894
+ export function use${componentName}Query<T = ${componentName}Return>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
895
+ return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
889
896
  { enabled: ${enabledParam}, ...options }
890
897
  );}
891
898
 
@@ -939,9 +946,8 @@ export const importOpenApi = async ({ data, format, apiDirectory, queryClientDir
939
946
  UseMutationOptions,
940
947
  QueryKey,
941
948
  SetDataOptions,
942
- QueryFilters
943
949
  } from 'react-query';
944
- import { Updater } from 'react-query/types/core/utils';
950
+ import { Updater, QueryFilters } from 'react-query/types/core/utils';
945
951
 
946
952
  import queryString from 'query-string';
947
953
  import { AxiosError } from 'axios';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-query-lightbase-codegen",
3
- "version": "0.1.7",
3
+ "version": "0.1.10",
4
4
  "license": "MIT",
5
5
  "main": "./lib/cjs/index.js",
6
6
  "module": "./lib/esm/index.js",
@@ -1,39 +0,0 @@
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
- });
@@ -1,8 +0,0 @@
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
- program
6
- .version(version)
7
- .command('import [open-api-file]', 'generate react-query hooks from OpenAPI specs')
8
- .parse(process.argv);
@@ -1,605 +0,0 @@
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 += `
366
- type ${componentName}Params = {${paramsTypes}};
367
- use${componentName}Query.fetch = async (props: ${componentName}Params ) => {
368
- const result = await api.${verb}<${genericsTypes}>(\`${route.replace(/\{/g, '{props.')}\`);
369
- return result.data;
370
- }
371
-
372
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
373
- use${componentName}Query.queryKey = (params: ${componentName}Params ): QueryKey => [...use${componentName}Query.baseKey(), params];
374
-
375
- type ${componentName}QueryProps<T = ${genericsTypes}> = {
376
- options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
377
- } & ${componentName}Params
378
-
379
- export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
380
- return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
381
- { enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
382
- );}
383
-
384
- type ${componentName}MutationProps<T> = {
385
- options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}Params, T>
386
- }
387
- export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
388
- return useMutation(async ({${paramsInPath.join(', ')}}) => {
389
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`)
390
- return result.data
391
- },
392
- props?.options
393
- )};`;
394
- }
395
- if (!requestBodyComponent && paramsInPath.length && queryParam) {
396
- output += `
397
- type ${componentName}Params = {
398
- ${paramsTypes}
399
- ${queryParamsType}
400
- }
401
-
402
- use${componentName}Query.fetch = async (props: ${componentName}Params) => {
403
- const {${paramsInPath.join(', ')}, ...queryParams} = props
404
- const params = queryString.stringify(queryParams);
405
- const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
406
- return result.data;
407
- }
408
-
409
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
410
-
411
- use${componentName}Query.queryKey = (params: ${componentName}Params): QueryKey => [...use${componentName}Query.baseKey(), params];
412
-
413
- type ${componentName}QueryProps<T = ${genericsTypes}> = {
414
- options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
415
- } & ${componentName}Params
416
-
417
- export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
418
- return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props), { enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
419
- );}
420
-
421
- type ${componentName}MutationProps<T> = {
422
- options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}Params, T>
423
- }
424
-
425
- export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
426
- return useMutation(async (data) => {
427
- const {${paramsInPath.join(', ')}, ...queryParams} = data
428
- const params = queryString.stringify(queryParams);
429
- const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
430
- return result.data
431
- },
432
- props?.options
433
- )};`;
434
- }
435
- if (!requestBodyComponent && !paramsInPath.length && !queryParam) {
436
- output += `
437
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
438
- use${componentName}Query.queryKey = (): QueryKey => use${componentName}Query.baseKey()
439
-
440
- use${componentName}Query.fetch = async () => {
441
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`);
442
- return result.data;
443
- }
444
-
445
- type ${componentName}QueryProps<T = ${genericsTypes}> = {
446
- options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
447
- }
448
-
449
- export function use${componentName}Query<T = ${genericsTypes}>(props?: ${componentName}QueryProps<T>) {
450
- return useQuery(use${componentName}Query.queryKey(), use${componentName}Query.fetch, props?.options
451
- );}
452
-
453
- type ${componentName}MutationProps<T> = {
454
- options?: UseMutationOptions<${genericsTypes}, AxiosError, void, T>
455
- }
456
- export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
457
- return useMutation(async () => {
458
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`);
459
- return result.data;
460
- },
461
- props?.options
462
- )};
463
- `;
464
- }
465
- if (!requestBodyComponent && !paramsInPath.length && queryParam) {
466
- output += `
467
- type ${componentName}Params = {
468
- ${queryParamsType}
469
- }
470
-
471
- use${componentName}Query.fetch = async (props: ${componentName}Params) => {
472
- const params = queryString.stringify({${queryParams
473
- .map((param) => `${param.name}: props.${param.name}`)
474
- .join(',')}});
475
- const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
476
- return result.data;
477
- }
478
-
479
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
480
- use${componentName}Query.queryKey = (params: ${componentName}Params ): QueryKey => [...use${componentName}Query.baseKey(), params];
481
-
482
-
483
- type ${componentName}QueryProps<T = ${genericsTypes}> = {
484
- options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
485
- } & ${componentName}Params
486
-
487
- export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
488
- return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props),
489
- {
490
- enabled: !!props.${queryParams.map((param) => param.name).join(' && !!props.')},
491
- ...options
492
- }
493
- );}
494
-
495
- type ${componentName}MutationProps<T> = {
496
- options?: UseMutationOptions<${genericsTypes}, AxiosError, ${componentName}Params, T>
497
- }
498
-
499
- export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
500
- return useMutation(async (data) => {
501
- const params = queryString.stringify({${queryParams
502
- .map((param) => `${param.name}: data.${param.name}`)
503
- .join(',')}});
504
- const result = await api.${verb}<${genericsTypes}>(\`${route}?\${params}\`)
505
- return result.data;
506
- },
507
- props?.options
508
- )};`;
509
- }
510
- if (requestBodyComponent && !paramsInPath.length && !queryParam) {
511
- output += `
512
- use${componentName}Query.fetch = async (body:${requestBodyComponent}) => {
513
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
514
- return result.data
515
- }
516
-
517
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
518
- use${componentName}Query.queryKey = (params:${requestBodyComponent}): QueryKey => [...use${componentName}Query.baseKey(), params];
519
-
520
-
521
- type ${componentName}QueryProps<T = ${genericsTypes}> = {
522
- options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
523
- } & ${requestBodyComponent}
524
-
525
- export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...body }: ${componentName}QueryProps<T>) {
526
- return useQuery(use${componentName}Query.queryKey(body), async () => use${componentName}Query.fetch(body), options
527
- );}
528
-
529
- type ${componentName}MutationProps<T> = {
530
- options?: UseMutationOptions<${genericsTypes}, AxiosError, ${requestBodyComponent}, T>
531
- }
532
- export function use${componentName}Mutation<T = ${genericsTypes}>(props?: ${componentName}MutationProps<T>) {
533
- return useMutation(async (body) => {
534
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
535
- return result.data
536
- },
537
- props?.options
538
- )};`;
539
- }
540
- if (requestBodyComponent && paramsInPath.length && !queryParam) {
541
- output += `
542
- // HDHD
543
- type ${componentName}Params = {${paramsTypes}} & ${requestBodyComponent}
544
-
545
- use${componentName}Query.fetch = async (props: ${componentName}Params) => {
546
- const {${paramsInPath.join(', ')}, ...body} = props
547
- const result = await api.${verb}<${genericsTypes}>(\`${route}\`, body)
548
- return result.data
549
- }
550
-
551
- use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
552
- use${componentName}Query.queryKey = (params: ${componentName}Params ): QueryKey => [...use${componentName}Query.baseKey(), params];
553
-
554
-
555
- type ${componentName}QueryProps<T = ${genericsTypes}> = {
556
- options?: UseQueryOptions<${genericsTypes}, AxiosError, T, any>
557
- } & ${componentName}Params
558
-
559
- export function use${componentName}Query<T = ${genericsTypes}>({ options = {}, ...props }: ${componentName}QueryProps<T>) {
560
- return useQuery(use${componentName}Query.queryKey(props), async () => use${componentName}Query.fetch(props), { enabled: !!props.${paramsInPath.join(' && !!props.')}, ...options }
561
- );}
562
-
563
- type ${componentName}MutationProps<T> = {
564
- options?: UseMutationOptions<${genericsTypes}, AxiosError,${componentName}Params, 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;
package/lib/types.js DELETED
@@ -1 +0,0 @@
1
- export {};