react-query-lightbase-codegen 1.0.1 → 1.0.2

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 (36) hide show
  1. package/package.json +8 -28
  2. package/lib/commonjs/convertSwaggerFile.js +0 -37
  3. package/lib/commonjs/convertSwaggerFile.js.map +0 -1
  4. package/lib/commonjs/generateHooks.js +0 -492
  5. package/lib/commonjs/generateHooks.js.map +0 -1
  6. package/lib/commonjs/generateImports.js +0 -48
  7. package/lib/commonjs/generateImports.js.map +0 -1
  8. package/lib/commonjs/generateSchemas.js +0 -119
  9. package/lib/commonjs/generateSchemas.js.map +0 -1
  10. package/lib/commonjs/importSpecs.js +0 -117
  11. package/lib/commonjs/importSpecs.js.map +0 -1
  12. package/lib/commonjs/index.js +0 -22
  13. package/lib/commonjs/index.js.map +0 -1
  14. package/lib/commonjs/utils.js +0 -212
  15. package/lib/commonjs/utils.js.map +0 -1
  16. package/lib/src/convertSwaggerFile.js +0 -29
  17. package/lib/src/generateHooks.js +0 -249
  18. package/lib/src/generateImports.js +0 -29
  19. package/lib/src/generateSchemas.js +0 -108
  20. package/lib/src/importSpecs.js +0 -134
  21. package/lib/src/index.js +0 -7
  22. package/lib/src/utils.js +0 -172
  23. package/lib/typescript/convertSwaggerFile.d.ts +0 -5
  24. package/lib/typescript/generateHooks.d.ts +0 -25
  25. package/lib/typescript/generateImports.d.ts +0 -7
  26. package/lib/typescript/generateSchemas.d.ts +0 -7
  27. package/lib/typescript/importSpecs.d.ts +0 -15
  28. package/lib/typescript/index.d.ts +0 -3
  29. package/lib/typescript/utils.d.ts +0 -24
  30. package/src/convertSwaggerFile.ts +0 -25
  31. package/src/generateHooks.ts +0 -490
  32. package/src/generateImports.ts +0 -41
  33. package/src/generateSchemas.ts +0 -114
  34. package/src/importSpecs.ts +0 -110
  35. package/src/index.ts +0 -3
  36. package/src/utils.ts +0 -190
package/package.json CHANGED
@@ -1,16 +1,12 @@
1
1
  {
2
2
  "name": "react-query-lightbase-codegen",
3
3
  "description": "Fully typed react query code generation tool based on openApi specifications",
4
- "version": "1.0.1",
4
+ "version": "1.0.2",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
- "exports": "./src/index.js",
7
+ "exports": "./dist/index.js",
8
8
  "files": [
9
- "src",
10
- "lib",
11
- "!**/__tests__",
12
- "!**/__fixtures__",
13
- "!**/__mocks__"
9
+ "lib/"
14
10
  ],
15
11
  "keywords": [
16
12
  "rest",
@@ -39,14 +35,14 @@
39
35
  },
40
36
  "scripts": {
41
37
  "lint": "eslint . --ext .js,.jsx,.ts,.tsx",
42
- "tsc": "tsc -p tsconfig.json && tsc -p tsconfig-cjs.json",
43
- "test": "node test/script.mjs && prettier --check ./test/generated/**/*.tsx --write && eslint ./test/generated/**/*.tsx --fix",
44
- "prepare": "bob build"
38
+ "tsc": "tsc -p tsconfig.json",
39
+ "test": "yarn tsc && node test/script.mjs && prettier --check ./test/generated/**/*.tsx --write && eslint ./test/generated/**/*.tsx --fix",
40
+ "prepare": "husky install"
45
41
  },
46
42
  "dependencies": {
47
43
  "axios": "0.27.2",
48
44
  "case": "1.6.3",
49
- "chalk": "4.1.2",
45
+ "chalk": "5.0.1",
50
46
  "js-yaml": "4.1.0",
51
47
  "lodash": "4.17.21",
52
48
  "openapi3-ts": "2.0.2",
@@ -75,23 +71,7 @@
75
71
  "husky": "^8.0.1",
76
72
  "prettier": "2.7.1",
77
73
  "react": "17.0.2",
78
- "react-native-builder-bob": "^0.18.3",
79
74
  "semantic-release": "^19.0.3",
80
75
  "typescript": "4.7.4"
81
- },
82
- "main": "lib/commonjs/index.js",
83
- "react-native": "src/index.ts",
84
- "types": "lib/typescript/src/index.d.ts",
85
- "react-native-builder-bob": {
86
- "source": "src",
87
- "output": "lib",
88
- "targets": [
89
- "commonjs",
90
- "typescript"
91
- ]
92
- },
93
- "eslintIgnore": [
94
- "node_modules/",
95
- "lib/"
96
- ]
76
+ }
97
77
  }
@@ -1,37 +0,0 @@
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
@@ -1 +0,0 @@
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"}
@@ -1,492 +0,0 @@
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