react-query-lightbase-codegen 0.3.0 → 1.0.1

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.
Files changed (45) hide show
  1. package/README.md +76 -0
  2. package/lib/commonjs/convertSwaggerFile.js +37 -0
  3. package/lib/commonjs/convertSwaggerFile.js.map +1 -0
  4. package/lib/commonjs/generateHooks.js +492 -0
  5. package/lib/commonjs/generateHooks.js.map +1 -0
  6. package/lib/commonjs/generateImports.js +48 -0
  7. package/lib/commonjs/generateImports.js.map +1 -0
  8. package/lib/commonjs/generateSchemas.js +119 -0
  9. package/lib/commonjs/generateSchemas.js.map +1 -0
  10. package/lib/commonjs/importSpecs.js +117 -0
  11. package/lib/commonjs/importSpecs.js.map +1 -0
  12. package/lib/commonjs/index.js +22 -0
  13. package/lib/commonjs/index.js.map +1 -0
  14. package/lib/commonjs/utils.js +212 -0
  15. package/lib/commonjs/utils.js.map +1 -0
  16. package/lib/src/convertSwaggerFile.js +29 -0
  17. package/lib/src/generateHooks.js +249 -0
  18. package/lib/src/generateImports.js +29 -0
  19. package/lib/src/generateSchemas.js +108 -0
  20. package/lib/src/importSpecs.js +134 -0
  21. package/lib/src/index.js +7 -0
  22. package/lib/src/utils.js +172 -0
  23. package/lib/typescript/convertSwaggerFile.d.ts +5 -0
  24. package/lib/typescript/generateHooks.d.ts +25 -0
  25. package/lib/typescript/generateImports.d.ts +7 -0
  26. package/lib/typescript/generateSchemas.d.ts +7 -0
  27. package/lib/typescript/importSpecs.d.ts +15 -0
  28. package/lib/typescript/index.d.ts +3 -0
  29. package/lib/typescript/utils.d.ts +24 -0
  30. package/package.json +71 -17
  31. package/src/convertSwaggerFile.ts +25 -0
  32. package/src/generateHooks.ts +490 -0
  33. package/src/generateImports.ts +41 -0
  34. package/src/generateSchemas.ts +114 -0
  35. package/src/importSpecs.ts +110 -0
  36. package/src/index.ts +3 -0
  37. package/src/utils.ts +190 -0
  38. package/lib/cjs/import-open-api.js +0 -1034
  39. package/lib/cjs/index.js +0 -5
  40. package/lib/cjs/react-query-codegen-import.js +0 -41
  41. package/lib/cjs/types.js +0 -2
  42. package/lib/esm/import-open-api.js +0 -1012
  43. package/lib/esm/index.js +0 -2
  44. package/lib/esm/react-query-codegen-import.js +0 -34
  45. package/lib/esm/types.js +0 -1
package/README.md CHANGED
@@ -1 +1,77 @@
1
+ # React Query Code Generation
1
2
 
3
+ Generate fully typed react query hooks from OpenAPI specifications.
4
+
5
+ - GET requests will automatically generate `useQuery` hooks together with helper functions
6
+ - getQueryState
7
+ - getQueryData
8
+ - prefetch
9
+ - cancelQueries
10
+ - invalidate
11
+ - refetchStale
12
+
13
+ - Override default generation forcing query, mutation or infiniteQuery output
14
+
15
+ ## Installation
16
+
17
+ You can install react-query-lightbase-codegen with NPM or Yarn.
18
+
19
+ Using NPM:
20
+
21
+ ```bash
22
+ $ npm i -D react-query-lightbase-codegen
23
+ ```
24
+
25
+ Using Yarn:
26
+
27
+ ```
28
+ $ yarn add -D react-query-lightbase-codegen
29
+ ```
30
+
31
+ ## Configuration
32
+
33
+ create a generateQueries.mjs file in project root folder
34
+
35
+ ```javascript
36
+ // generateQueries.mjs
37
+ import { importSpecs } from 'react-query-lightbase-codegen';
38
+
39
+ importSpecs({
40
+ // folder location of the openapi/swagger documents (yaml or JSON)
41
+ sourceDirectory: './specs',
42
+ // export folder for hooks and schema code generated files
43
+ exportDirectory: './src/generated',
44
+ // api client - as named export labelled 'api'
45
+ apiDirectory: './src/api',
46
+ // React query client directory - names export 'queryClient'
47
+ queryClientDir: './src/api',
48
+ });
49
+ ```
50
+
51
+ ## Code generation
52
+
53
+ To generate the code generated scheme and react query hooks run the above script
54
+
55
+ ```bash
56
+ node scripts/generateQueries.mjs && prettier --check ./src/generated/*.tsx --write
57
+ ```
58
+
59
+ ## Configuration Options
60
+
61
+ ```javascript
62
+ // generateQueries.mjs
63
+ import { importSpecs } from 'react-query-lightbase-codegen';
64
+
65
+ importSpecs({
66
+ ...
67
+ // Filter out any headers from individual queries (these might be applied globally in the axios instance)
68
+ headerFilters: ['X-Session-Token'],
69
+ overrides: {
70
+ // operationId listed in the openApi spec
71
+ findPetsByStatus: {
72
+ // Override the default query code generation type ('query' | 'mutation' | 'infiniteQuery')
73
+ type: 'query',
74
+ },
75
+ },
76
+ });
77
+ ```
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.convertSwaggerFile = void 0;
7
+
8
+ var _swagger2openapi = _interopRequireDefault(require("swagger2openapi"));
9
+
10
+ var _jsYaml = _interopRequireDefault(require("js-yaml"));
11
+
12
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13
+
14
+ /**
15
+ * Import and parse the openapi spec from a yaml/json
16
+ */
17
+ const convertSwaggerFile = (data, extension) => {
18
+ const schema = extension === 'yaml' ? _jsYaml.default.load(data) : JSON.parse(data);
19
+ return new Promise((resolve, reject) => {
20
+ if (!schema.openapi || !schema.openapi.startsWith('3.')) {
21
+ _swagger2openapi.default.convertObj(schema, {}, (err, convertedObj) => {
22
+ if (err) {
23
+ reject(err);
24
+ } else {
25
+ // @ts-ignore
26
+ convertedObj.openapi.basePath = convertedObj.original.basePath;
27
+ resolve(convertedObj.openapi);
28
+ }
29
+ });
30
+ } else {
31
+ resolve(schema);
32
+ }
33
+ });
34
+ };
35
+
36
+ exports.convertSwaggerFile = convertSwaggerFile;
37
+ //# sourceMappingURL=convertSwaggerFile.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["convertSwaggerFile","data","extension","schema","yaml","load","JSON","parse","Promise","resolve","reject","openapi","startsWith","swagger2openapi","convertObj","err","convertedObj","basePath","original"],"sources":["convertSwaggerFile.ts"],"sourcesContent":["import { OpenAPIObject } from 'openapi3-ts';\nimport swagger2openapi from 'swagger2openapi';\nimport yaml from 'js-yaml';\n\n/**\n * Import and parse the openapi spec from a yaml/json\n */\nexport const convertSwaggerFile = (data: string, extension: 'yaml' | 'json'): Promise<OpenAPIObject> => {\n const schema = extension === 'yaml' ? yaml.load(data) : JSON.parse(data);\n return new Promise((resolve, reject) => {\n if (!schema.openapi || !schema.openapi.startsWith('3.')) {\n swagger2openapi.convertObj(schema, {}, (err, convertedObj) => {\n if (err) {\n reject(err);\n } else {\n // @ts-ignore\n convertedObj.openapi.basePath = convertedObj.original.basePath;\n resolve(convertedObj.openapi);\n }\n });\n } else {\n resolve(schema);\n }\n });\n};\n"],"mappings":";;;;;;;AACA;;AACA;;;;AAEA;AACA;AACA;AACO,MAAMA,kBAAkB,GAAG,CAACC,IAAD,EAAeC,SAAf,KAAsE;EACtG,MAAMC,MAAM,GAAGD,SAAS,KAAK,MAAd,GAAuBE,eAAA,CAAKC,IAAL,CAAUJ,IAAV,CAAvB,GAAyCK,IAAI,CAACC,KAAL,CAAWN,IAAX,CAAxD;EACA,OAAO,IAAIO,OAAJ,CAAY,CAACC,OAAD,EAAUC,MAAV,KAAqB;IACtC,IAAI,CAACP,MAAM,CAACQ,OAAR,IAAmB,CAACR,MAAM,CAACQ,OAAP,CAAeC,UAAf,CAA0B,IAA1B,CAAxB,EAAyD;MACvDC,wBAAA,CAAgBC,UAAhB,CAA2BX,MAA3B,EAAmC,EAAnC,EAAuC,CAACY,GAAD,EAAMC,YAAN,KAAuB;QAC5D,IAAID,GAAJ,EAAS;UACPL,MAAM,CAACK,GAAD,CAAN;QACD,CAFD,MAEO;UACL;UACAC,YAAY,CAACL,OAAb,CAAqBM,QAArB,GAAgCD,YAAY,CAACE,QAAb,CAAsBD,QAAtD;UACAR,OAAO,CAACO,YAAY,CAACL,OAAd,CAAP;QACD;MACF,CARD;IASD,CAVD,MAUO;MACLF,OAAO,CAACN,MAAD,CAAP;IACD;EACF,CAdM,CAAP;AAeD,CAjBM"}
@@ -0,0 +1,492 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.createHook = void 0;
7
+
8
+ var _lodash = _interopRequireDefault(require("lodash"));
9
+
10
+ var _utils = require("./utils.js");
11
+
12
+ var _case = _interopRequireDefault(require("case"));
13
+
14
+ var _chalk = _interopRequireDefault(require("chalk"));
15
+
16
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17
+
18
+ const {
19
+ get,
20
+ groupBy
21
+ } = _lodash.default;
22
+ const {
23
+ pascal,
24
+ camel
25
+ } = _case.default;
26
+ const IdentifierRegexp = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
27
+ /**
28
+ * Return every params in a path
29
+ */
30
+
31
+ const getParamsInPath = path => {
32
+ let n;
33
+ const output = [];
34
+ const templatePathRegex = /\{(\w+)}/g;
35
+
36
+ while ((n = templatePathRegex.exec(path)) !== null) {
37
+ output.push(n[1]);
38
+ }
39
+
40
+ return output;
41
+ };
42
+ /**
43
+ * Generate a react-query component from openapi operation specs
44
+ */
45
+
46
+
47
+ const createHook = _ref => {
48
+ let {
49
+ operation,
50
+ verb,
51
+ route,
52
+ operationIds,
53
+ parameters,
54
+ schemasComponents,
55
+ headerFilters,
56
+ overrides
57
+ } = _ref;
58
+ const {
59
+ operationId = route.replace('/', '')
60
+ } = operation;
61
+
62
+ if (operationId === '*') {
63
+ throw new Error(`Invalid operationId/Route set for ${verb} ${route}`);
64
+ }
65
+
66
+ if (operationIds.includes(operationId)) {
67
+ return {
68
+ implementation: '',
69
+ imports: [],
70
+ queryImports: []
71
+ };
72
+ }
73
+
74
+ operationIds.push(operationId);
75
+ route = route.replace(/\{/g, '${').replace('//', '/'); // `/pet/{id}` => `/pet/${id}`
76
+ // Remove the last param of the route if we are in the DELETE case
77
+
78
+ let lastParamInTheRoute = null;
79
+ const componentName = pascal(operationId);
80
+
81
+ const isOk = _ref2 => {
82
+ let [statusCode] = _ref2;
83
+ return statusCode.toString().startsWith('2');
84
+ };
85
+
86
+ const responseTypes = (0, _utils.getResReqTypes)(Object.entries(operation.responses).filter(isOk)) || 'void';
87
+ const requestBodyTypes = (0, _utils.getResReqTypes)([['body', operation.requestBody]]);
88
+ let imports = [responseTypes];
89
+ let queryImports = [];
90
+ const paramsInPath = getParamsInPath(route).filter(param => !(verb === 'delete' && param === lastParamInTheRoute));
91
+ const {
92
+ query: queryParams = [],
93
+ path: pathParams = [],
94
+ header = []
95
+ } = groupBy([...(parameters || []), ...(operation.parameters || [])].map(p => {
96
+ if ((0, _utils.isReference)(p)) {
97
+ return get(schemasComponents, p.$ref.replace('#/components/', '').replace('/', '.'));
98
+ } else {
99
+ return p;
100
+ }
101
+ }), 'in');
102
+ const headerParams = header.filter(p => !(headerFilters !== null && headerFilters !== void 0 && headerFilters.includes(p.name)));
103
+ let enabled = []; // TODO: extract all requestBody or remove useQuery variants
104
+
105
+ let enabledParam = '!!params';
106
+ [...queryParams, ...pathParams, ...headerParams].forEach(item => {
107
+ if (item.required) {
108
+ enabled.push(`["${item.name}"]`);
109
+
110
+ if (enabledParam && enabledParam !== '!!params') {
111
+ enabledParam += `&& params['${item.name}'] != null`;
112
+ } else {
113
+ enabledParam = `params['${item.name}'] != null`;
114
+ }
115
+ }
116
+ }); // `!props${enabled.join('== null && !props')}`;
117
+
118
+ const paramsTypes = paramsInPath.map(p => {
119
+ try {
120
+ const {
121
+ name,
122
+ required,
123
+ schema
124
+ } = pathParams.find(i => i.name === p);
125
+ return `${name}${required ? '' : '?'}: ${(0, _utils.resolveValue)(schema)}`;
126
+ } catch (err) {
127
+ throw new Error(`The path params ${p} can't be found in parameters (${operationId})`);
128
+ }
129
+ }).join('; ');
130
+ const queryParamsType = queryParams.map(p => {
131
+ const processedName = IdentifierRegexp.test(p.name) ? p.name : `"${p.name}"`;
132
+ return `${(0, _utils.formatDescription)(p.description)}
133
+ ${processedName}${p.required ? '' : '?'}: ${(0, _utils.resolveValue)(p.schema)}`;
134
+ }).join(';\n ');
135
+ const headerType = headerParams.map(p => {
136
+ try {
137
+ const {
138
+ name,
139
+ required,
140
+ schema
141
+ } = headerParams.find(i => i.name === p.name);
142
+ return `"${name}"${required ? '' : '?'}: ${(0, _utils.resolveValue)(schema)}`;
143
+ } catch (err) {
144
+ throw new Error(`The path params ${p} can't be found in parameters (${operationId})`);
145
+ }
146
+ }).join('; '); // Retrieve the type of the param for delete verb
147
+
148
+ const lastParamInTheRouteDefinition = operation.parameters && lastParamInTheRoute ? operation.parameters.find(p => {
149
+ if ((0, _utils.isReference)(p)) {
150
+ return false;
151
+ }
152
+
153
+ return p.name === lastParamInTheRoute;
154
+ }) // Reference is not possible
155
+ : {
156
+ schema: {
157
+ type: 'string'
158
+ }
159
+ };
160
+
161
+ if (!lastParamInTheRouteDefinition) {
162
+ throw new Error(`The path params ${lastParamInTheRoute} can't be found in parameters (${operationId})`);
163
+ }
164
+
165
+ const defaultDescription = `type: ${verb}\noperationId: ${operationId}\nurl: ${route}`;
166
+ const description = (0, _utils.formatDescription)(operation.summary && operation.description ? `${defaultDescription}\n\n${operation.summary}\n\n${operation.description}` : `${defaultDescription}`);
167
+ let output = `\n\n${description}`;
168
+ const headerParam = headerType && headerType !== 'void' ? `${headerType};` : '';
169
+ const queryParam = queryParamsType && queryParamsType !== 'void' ? `${queryParamsType}` : '';
170
+ const requestBodyComponent = requestBodyTypes && requestBodyTypes !== 'void' ? `${requestBodyTypes}` : '';
171
+
172
+ if (requestBodyComponent) {
173
+ imports.push(requestBodyComponent);
174
+ }
175
+
176
+ const isUpdateRequest = ['post', 'patch', 'put'].includes(verb);
177
+
178
+ const generateProps = props => {
179
+ return props.map(item => `["${item.name}"]: props["${item.name}"]`).join(',');
180
+ };
181
+
182
+ const generateBodyProps = () => {
183
+ const definitionKey = Object.keys((schemasComponents === null || schemasComponents === void 0 ? void 0 : schemasComponents.schemas) || {}).find(key => pascal(key) === requestBodyComponent);
184
+
185
+ if (definitionKey) {
186
+ var _schemasComponents$sc;
187
+
188
+ const scheme = schemasComponents === null || schemasComponents === void 0 ? void 0 : (_schemasComponents$sc = schemasComponents.schemas) === null || _schemasComponents$sc === void 0 ? void 0 : _schemasComponents$sc[definitionKey];
189
+ return Object.keys(scheme.properties).map(item => `["${item}"]: props["${item}"]`).join(',');
190
+ }
191
+ };
192
+
193
+ const fetchName = camel(componentName);
194
+
195
+ const createQueryHooks = emptyParams => {
196
+ const params = emptyParams ? '' : `params: ${componentName}Params,`;
197
+ const key = emptyParams ? '' : `params`;
198
+ const mutationParams = emptyParams ? 'void' : `${componentName}Params`;
199
+ const queryParamType = emptyParams ? '' : `${componentName}Params &`;
200
+ const filterParams = emptyParams ? '{ filters }: { filters?: QueryFilters }' : `{ params, filters }: { params: ${componentName}Params, filters?: QueryFilters }`;
201
+ const cacheParams = emptyParams ? `{updater, options}: {updater: Updater<${responseTypes} | undefined, ${responseTypes} | undefined>, options?: SetDataOptions | undefined}` : `{params, updater, options}: {params: ${componentName}Params, updater: Updater<${responseTypes} | undefined, ${responseTypes} | undefined>, options?: SetDataOptions | undefined}`;
202
+ const queryKey = emptyParams ? `use${componentName}Query.baseKey()` : `[...use${componentName}Query.baseKey(), params]`;
203
+
204
+ const createQuery = () => `
205
+ type ${componentName}QueryProps<T = ${responseTypes}> = ${queryParamType} {
206
+ options?: UseQueryOptions<${responseTypes}, AxiosError, T, any>
207
+ }
208
+ export function use${componentName}Query<T = ${responseTypes}>({ options = {}, ...params }: ${componentName}QueryProps<T>) {
209
+ return useQuery(use${componentName}Query.queryKey(${key}), async () => ${fetchName}(${key}), { enabled: ${enabledParam}, ...options });
210
+ }
211
+
212
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
213
+
214
+ use${componentName}Query.queryKey = (${params}): QueryKey => ${queryKey};
215
+
216
+ use${componentName}Query.updateCache = (${cacheParams}) => queryClient.setQueryData<${responseTypes}>(use${componentName}Query.queryKey(${key}), updater, options);
217
+
218
+ use${componentName}Query.getQueryState = (${filterParams})=> queryClient.getQueryState<${responseTypes}>(use${componentName}Query.queryKey(${key}), filters);
219
+
220
+ use${componentName}Query.getQueryData = (${filterParams})=> queryClient.getQueryData<${responseTypes}>(use${componentName}Query.queryKey(${key}), filters);
221
+
222
+ use${componentName}Query.prefetch = (${params}) => queryClient.prefetchQuery<${responseTypes}>(use${componentName}Query.queryKey(${key}), ()=> ${fetchName}(${key}));
223
+
224
+ use${componentName}Query.cancelQueries = (${params}) => queryClient.cancelQueries(use${componentName}Query.queryKey(${key}))
225
+
226
+ use${componentName}Query.invalidate = (${params}) => queryClient.invalidateQueries<${responseTypes}>(use${componentName}Query.queryKey(${key}));
227
+
228
+ use${componentName}Query.refetchStale = (${params}) => queryClient.refetchQueries<${responseTypes}>(use${componentName}Query.queryKey(${key}), { stale: true });
229
+ `;
230
+
231
+ const getInfiniteQuery = _ref3 => {
232
+ let {
233
+ pageParam
234
+ } = _ref3;
235
+ return `
236
+ type ${componentName}QueryProps<T = ${responseTypes}> = ${queryParamType} {
237
+ options: UseInfiniteQueryOptions<${responseTypes}, AxiosError, T, any>
238
+ }
239
+ export function use${componentName}Query<T = ${responseTypes}>({ options = {}, ...params }: ${componentName}QueryProps<T>) {
240
+ return useInfiniteQuery(use${componentName}Query.queryKey(${key}), async ({ pageParam = 0 }) => ${fetchName}({${pageParam}: pageParam, ...params}), { enabled: ${enabledParam}, ...options });
241
+ }
242
+
243
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
244
+
245
+ use${componentName}Query.queryKey = (${params}): QueryKey => ${queryKey};
246
+
247
+ `;
248
+ };
249
+
250
+ const createMutation = () => `
251
+ type ${componentName}MutationProps<T> = {
252
+ options?: UseMutationOptions<${responseTypes}, AxiosError, ${mutationParams}, T>
253
+ }
254
+ export function use${componentName}Mutation<T = ${responseTypes}>(props?: ${componentName}MutationProps<T>) {
255
+ return useMutation(async (${key}) => ${fetchName}(${key}), props?.options)
256
+ };
257
+ `;
258
+
259
+ const override = overrides === null || overrides === void 0 ? void 0 : overrides[operationId];
260
+
261
+ if ((override === null || override === void 0 ? void 0 : override.type) === 'query') {
262
+ console.log(_chalk.default.blue(`⚙️ [${operationId}] has been changed to a useQuery hook`));
263
+ queryImports.push('query');
264
+ return createQuery();
265
+ }
266
+
267
+ if ((override === null || override === void 0 ? void 0 : override.type) === 'mutation') {
268
+ queryImports.push('mutation');
269
+ console.log(_chalk.default.blue(`⚙️ [${operationId}] has been changed to a useMutation hook`));
270
+ return createMutation();
271
+ }
272
+
273
+ if ((override === null || override === void 0 ? void 0 : override.type) === 'infiniteQuery') {
274
+ console.log(_chalk.default.blue(`⚙️ [${operationId}] has been changed to a useInfiniteQuery hook`));
275
+ queryImports.push('infiniteQuery');
276
+ return getInfiniteQuery({
277
+ pageParam: override.infiniteQueryParm
278
+ });
279
+ }
280
+
281
+ if (verb === 'get') {
282
+ queryImports.push('query');
283
+ return createQuery();
284
+ }
285
+
286
+ queryImports.push('mutation');
287
+ return createMutation();
288
+ };
289
+
290
+ output += createQueryHooks(!requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam);
291
+
292
+ if (!requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
293
+ output += `
294
+ const ${fetchName} = async () => {
295
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`);
296
+ return result.data;
297
+ }
298
+ `;
299
+ }
300
+
301
+ if (!requestBodyComponent && paramsInPath.length && queryParam && !headerParam) {
302
+ const config = isUpdateRequest ? 'body,{params}' : '{params}';
303
+ output += `
304
+ type ${componentName}Params = {
305
+ ${paramsTypes}
306
+ ${queryParamsType};
307
+ }
308
+
309
+ const ${fetchName} = async (props:${componentName}Params) => {
310
+ const {${paramsInPath.join(', ')}, ...params} = props
311
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config})
312
+ return result.data;
313
+ }`;
314
+ }
315
+
316
+ if (!requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
317
+ output += `
318
+ type ${componentName}Params = {
319
+ ${paramsTypes}
320
+ }
321
+
322
+ const ${fetchName} = async (props: ${componentName}Params ) => {
323
+ const result = await api.${verb}<${responseTypes}>(\`${route.replace(/\{/g, '{props.')}\`);
324
+ return result.data;
325
+ }
326
+ `;
327
+ }
328
+
329
+ if (!requestBodyComponent && !paramsInPath.length && queryParam && !headerParam) {
330
+ const config = isUpdateRequest ? 'null,{params}' : '{params}';
331
+ output += `
332
+ type ${componentName}Params = {
333
+ ${queryParamsType}
334
+ }
335
+
336
+ const ${fetchName} = async (params: ${componentName}Params) => {
337
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config})
338
+ return result.data;
339
+ }
340
+ `;
341
+ }
342
+
343
+ if (!requestBodyComponent && !paramsInPath.length && queryParam && headerParam) {
344
+ const config = isUpdateRequest ? 'null,{headers, params: queryParams}' : '{headers, params: queryParams}';
345
+ output += `
346
+ type ${componentName}Params = {
347
+ ${headerParam}
348
+ ${queryParamsType}
349
+ }
350
+ const ${fetchName} = async (props: ${componentName}Params) => {
351
+ const headers = {${generateProps(header)}}
352
+ const queryParams = {${generateProps(queryParams)}}
353
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config})
354
+ return result.data
355
+ }`;
356
+ }
357
+
358
+ if (!requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
359
+ const config = isUpdateRequest ? 'null,{headers}' : '{headers}';
360
+ output += `
361
+ type ${componentName}Params = {
362
+ ${headerParam}
363
+ };
364
+
365
+ const ${fetchName} = async (headers: ${componentName}Params) => {
366
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config});
367
+ return result.data;
368
+ }
369
+ `;
370
+ }
371
+
372
+ if (requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
373
+ output += `
374
+ type ${componentName}Params = ${requestBodyComponent}
375
+
376
+ const ${fetchName} = async (body: ${componentName}Params) => {
377
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, body)
378
+ return result.data
379
+ }
380
+ `;
381
+ }
382
+
383
+ if (requestBodyComponent && !paramsInPath.length && queryParam && !headerParam) {
384
+ const config = isUpdateRequest ? 'null,{headers, params: queryParams}' : '{headers, params: queryParams}';
385
+ const queryParamsProps = queryParams.map(item => `["${item.name}"]: props["${item.name}"]`);
386
+ output += `
387
+ type ${componentName}Params = ${requestBodyComponent} & {
388
+ ${queryParamsType}
389
+ }
390
+
391
+ type ${componentName}QueryProps<T = ${responseTypes}> = ${componentName}Params & {
392
+ const body = {${generateBodyProps()}}
393
+ const params = {${generateProps(queryParams)}}
394
+ options?: UseQueryOptions<${responseTypes}, AxiosError, T, any>
395
+ }
396
+
397
+ const ${fetchName} = async ({body, params}: ${componentName}Params) => {
398
+ const queryParams = {${queryParamsProps.join(',')}}
399
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config})
400
+ return result.data
401
+ }
402
+ `;
403
+ }
404
+
405
+ if (requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
406
+ output += `
407
+ type ${componentName}Params = ${requestBodyComponent} & {
408
+ ${headerParam}
409
+ };
410
+
411
+ const ${fetchName} = async (props: ${componentName}Params) => {
412
+ const headers = {${generateProps(header)}}
413
+ const body = {${generateBodyProps()}}
414
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, body, {headers})
415
+ return result.data
416
+ }
417
+ `;
418
+ }
419
+
420
+ if (requestBodyComponent && !paramsInPath.length && queryParam && headerParam) {
421
+ output += `
422
+ type ${componentName}Params = ${requestBodyComponent} & {
423
+ ${headerParam}
424
+ ${paramsTypes}
425
+ };
426
+
427
+ const ${fetchName} = async (props: ${componentName}Params) => {
428
+ const body = {${generateBodyProps()}}
429
+ const headers = {${generateProps(header)}}
430
+ const params = {${generateProps(queryParams)}}
431
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, body, {headers, params})
432
+ return result.data
433
+ }
434
+ `;
435
+ }
436
+
437
+ if (requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
438
+ output += `
439
+ type ${componentName}Params = ${requestBodyComponent} & {
440
+ ${headerParam}
441
+ ${paramsTypes}
442
+ };
443
+
444
+ const ${fetchName} = async (props: ${componentName}Params) => {
445
+ const body = {${generateBodyProps()}}
446
+ const result = await api.${verb}<${responseTypes}>(\`${route.replace(/\{/g, '{props.')}\`, body)
447
+ return result.data
448
+ }
449
+ `;
450
+ }
451
+
452
+ if (requestBodyComponent && paramsInPath.length && queryParam && !headerParam) {
453
+ output += `// TODO: NOT SUPPORTED requestBodyComponent && paramsInPath && queryParam)`;
454
+ }
455
+
456
+ if (requestBodyComponent && paramsInPath.length && queryParam && headerParam) {
457
+ output += `// TODO: NOT SUPPORTED requestBodyComponent && paramsInPath && queryParam && headerParam)`;
458
+ }
459
+
460
+ if (!requestBodyComponent && paramsInPath.length && !queryParam && headerParam) {
461
+ const config = isUpdateRequest ? 'null,{headers}' : '{headers}';
462
+ output += `
463
+ type ${componentName}Params = {
464
+ ${headerParam}
465
+ ${paramsTypes}
466
+ };
467
+
468
+ const ${fetchName} = async (props: ${componentName}Params) => {
469
+ const headers = {${generateProps(header)}}
470
+ const result = await api.${verb}<${responseTypes}>(\`${route.replace(/\{/g, '{props.')}\`, ${config})
471
+ return result.data
472
+ }
473
+ `;
474
+ }
475
+
476
+ if (!requestBodyComponent && paramsInPath.length && queryParam && headerParam) {
477
+ output += `// TODO: NOT SUPPORTED (paramsInPath && queryParam && headerParam)`;
478
+ }
479
+
480
+ if (requestBodyComponent && paramsInPath.length && !queryParam && headerParam) {
481
+ output += `// TODO: NOT SUPPORTED (requestBodyComponent && paramsInPath && headerParam)`;
482
+ }
483
+
484
+ return {
485
+ implementation: output,
486
+ imports,
487
+ queryImports
488
+ };
489
+ };
490
+
491
+ exports.createHook = createHook;
492
+ //# sourceMappingURL=generateHooks.js.map