react-query-lightbase-codegen 1.1.0 → 1.1.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.
@@ -0,0 +1,165 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getResReqTypes = exports.formatDescription = exports.resolveValue = exports.getScalar = exports.isReference = exports.getDocs = void 0;
7
+ const lodash_1 = __importDefault(require("lodash"));
8
+ const { uniq, isEmpty } = lodash_1.default;
9
+ const case_1 = __importDefault(require("case"));
10
+ const { pascal } = case_1.default;
11
+ const getDocs = (data) => (0, exports.isReference)(data) ? '' : (0, exports.formatDescription)(data.description);
12
+ exports.getDocs = getDocs;
13
+ /**
14
+ * Discriminator helper for `ReferenceObject`
15
+ */
16
+ const isReference = (property) => {
17
+ return Boolean(property.$ref);
18
+ };
19
+ exports.isReference = isReference;
20
+ /**
21
+ * Return the typescript equivalent of open-api data type
22
+ */
23
+ const getScalar = (item) => {
24
+ const nullable = item.nullable ? ' | null' : '';
25
+ switch (item.type) {
26
+ case 'number':
27
+ case 'integer':
28
+ return 'number' + nullable;
29
+ case 'boolean':
30
+ return 'boolean' + nullable;
31
+ case 'array':
32
+ return getArray(item) + nullable;
33
+ case 'string':
34
+ return (item.enum ? `"${item.enum.join(`" | "`)}"` : 'string') + nullable;
35
+ case 'object':
36
+ default:
37
+ return getObject(item) + nullable;
38
+ }
39
+ };
40
+ exports.getScalar = getScalar;
41
+ /**
42
+ * Return the output type from the $ref
43
+ */
44
+ const getRef = ($ref) => {
45
+ if ($ref.startsWith('#/components/schemas')) {
46
+ return pascal($ref.replace('#/components/schemas/', ''));
47
+ }
48
+ else if ($ref.startsWith('#/components/responses')) {
49
+ return pascal($ref.replace('#/components/responses/', '')) + 'Response';
50
+ }
51
+ else if ($ref.startsWith('#/components/parameters')) {
52
+ return pascal($ref.replace('#/components/parameters/', '')) + 'Parameter';
53
+ }
54
+ else if ($ref.startsWith('#/components/requestBodies')) {
55
+ return pascal($ref.replace('#/components/requestBodies/', '')) + 'RequestBody';
56
+ }
57
+ else {
58
+ throw new Error('This library only resolve $ref that are include into `#/components/*` for now');
59
+ }
60
+ };
61
+ /**
62
+ * Return the output type from an array
63
+ */
64
+ const getArray = (item) => {
65
+ if (item.items) {
66
+ if (!(0, exports.isReference)(item.items) && (item.items.oneOf || item.items.allOf || item.items.enum)) {
67
+ return `(${(0, exports.resolveValue)(item.items)})[]`;
68
+ }
69
+ else {
70
+ return `${(0, exports.resolveValue)(item.items)}[]`;
71
+ }
72
+ }
73
+ else {
74
+ throw new Error('All arrays must have an `items` key define');
75
+ }
76
+ };
77
+ /**
78
+ * Return the output type from an object
79
+ */
80
+ const getObject = (item) => {
81
+ if ((0, exports.isReference)(item)) {
82
+ return getRef(item.$ref);
83
+ }
84
+ if (item.allOf) {
85
+ return item.allOf.map(exports.resolveValue).join(' & ');
86
+ }
87
+ if (item.oneOf) {
88
+ return item.oneOf.map(exports.resolveValue).join(' | ');
89
+ }
90
+ if (!item.type && !item.properties && !item.additionalProperties) {
91
+ return '{}';
92
+ }
93
+ // Free form object (https://swagger.io/docs/specification/data-models/data-types/#free-form)
94
+ if (item.type === 'object' &&
95
+ !item.properties &&
96
+ (!item.additionalProperties || item.additionalProperties === true || isEmpty(item.additionalProperties))) {
97
+ return '{[key: string]: any}';
98
+ }
99
+ const IdentifierRegexp = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
100
+ // Consolidation of item.properties & item.additionalProperties
101
+ let output = '{\n';
102
+ if (item.properties) {
103
+ output += Object.entries(item.properties)
104
+ .map(([key, prop]) => {
105
+ const doc = (0, exports.getDocs)(prop);
106
+ const isRequired = (item.required || []).includes(key);
107
+ const processedKey = IdentifierRegexp.test(key) ? key : `"${key}"`;
108
+ return `${doc}\n${processedKey}${isRequired ? '' : '?'}: ${(0, exports.resolveValue)(prop)};`;
109
+ })
110
+ .join('');
111
+ }
112
+ if (item.additionalProperties) {
113
+ if (item.properties) {
114
+ output += '\n';
115
+ }
116
+ output += `} & { [key: string]: ${item.additionalProperties === true ? 'any' : (0, exports.resolveValue)(item.additionalProperties)}`;
117
+ }
118
+ if (item.properties || item.additionalProperties) {
119
+ if (output === '{\n') {
120
+ return '{}';
121
+ }
122
+ return output + '\n}';
123
+ }
124
+ return item.type === 'object' ? '{[key: string]: any}' : 'any';
125
+ };
126
+ /**
127
+ * Resolve the value of a schema object to a proper type definition.
128
+ */
129
+ const resolveValue = (schema) => (0, exports.isReference)(schema) ? getRef(schema.$ref) : (0, exports.getScalar)(schema);
130
+ exports.resolveValue = resolveValue;
131
+ /**
132
+ * Format a description to code documentation.
133
+ */
134
+ const formatDescription = (description) => {
135
+ if (!description)
136
+ return '';
137
+ return `/**\n${description
138
+ .split('\n')
139
+ .map((i) => `* ${i}`)
140
+ .join('\n')}\n */`;
141
+ };
142
+ exports.formatDescription = formatDescription;
143
+ /**
144
+ * Extract responses / request types from open-api specs
145
+ */
146
+ const getResReqTypes = (responsesOrRequests) => uniq(responsesOrRequests.map(([_, res]) => {
147
+ if (!res) {
148
+ return;
149
+ }
150
+ if ((0, exports.isReference)(res)) {
151
+ return getRef(res.$ref);
152
+ }
153
+ if (res.content) {
154
+ for (let contentType of Object.keys(res.content)) {
155
+ if (contentType.startsWith('application/json') ||
156
+ contentType.startsWith('application/octet-stream')) {
157
+ const schema = res.content[contentType].schema;
158
+ return (0, exports.resolveValue)(schema);
159
+ }
160
+ }
161
+ return;
162
+ }
163
+ return;
164
+ })).join(' | ');
165
+ exports.getResReqTypes = getResReqTypes;
@@ -0,0 +1,25 @@
1
+ import swagger2openapi from 'swagger2openapi';
2
+ import yaml from 'js-yaml';
3
+ /**
4
+ * Import and parse the openapi spec from a yaml/json
5
+ */
6
+ export const convertSwaggerFile = (data, extension) => {
7
+ const schema = extension === 'yaml' ? yaml.load(data) : JSON.parse(data);
8
+ return new Promise((resolve, reject) => {
9
+ if (!schema.openapi || !schema.openapi.startsWith('3.')) {
10
+ swagger2openapi.convertObj(schema, {}, (err, convertedObj) => {
11
+ if (err) {
12
+ reject(err);
13
+ }
14
+ else {
15
+ // @ts-ignore
16
+ convertedObj.openapi.basePath = convertedObj.original.basePath;
17
+ resolve(convertedObj.openapi);
18
+ }
19
+ });
20
+ }
21
+ else {
22
+ resolve(schema);
23
+ }
24
+ });
25
+ };
@@ -0,0 +1,360 @@
1
+ import lodash from 'lodash';
2
+ const { get, groupBy, uniq } = lodash;
3
+ import { formatDescription, getResReqTypes, isReference, resolveValue } from './utils.js';
4
+ import pasCase from 'case';
5
+ const { pascal } = pasCase;
6
+ const IdentifierRegexp = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
7
+ /**
8
+ * Return every params in a path
9
+ */
10
+ const getParamsInPath = (path) => {
11
+ let n;
12
+ const output = [];
13
+ const templatePathRegex = /\{(\w+)}/g;
14
+ while ((n = templatePathRegex.exec(path)) !== null) {
15
+ output.push(n[1]);
16
+ }
17
+ return output;
18
+ };
19
+ const createQueryHooks = ({ componentName, responseTypes, enabledParam, emptyParams, }) => {
20
+ const params = emptyParams ? '' : `params: ${componentName}Params,`;
21
+ const key = emptyParams ? '' : `params`;
22
+ const mutationParams = emptyParams ? 'void' : `${componentName}Params`;
23
+ const queryParams = emptyParams ? '' : `${componentName}Params &`;
24
+ const filterParams = emptyParams
25
+ ? '{ filters }: { filters?: QueryFilters }'
26
+ : `{ params, filters }: { params: ${componentName}Params, filters }`;
27
+ const cacheParams = emptyParams
28
+ ? `{updater, options}: {updater: Updater<${responseTypes} | undefined, ${responseTypes} | undefined>, options?: SetDataOptions | undefined}`
29
+ : `{params, updater, options}: {params: ${componentName}Params, updater: Updater<${responseTypes} | undefined, ${responseTypes} | undefined>, options?: SetDataOptions | undefined}`;
30
+ const queryKey = emptyParams
31
+ ? `use${componentName}Query.baseKey()`
32
+ : `[...use${componentName}Query.baseKey(), params]`;
33
+ const query = `
34
+ use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
35
+
36
+ use${componentName}Query.queryKey = (${params}): QueryKey => ${queryKey};
37
+
38
+ use${componentName}Query.updateCache = (${cacheParams}) => queryClient.setQueryData<${responseTypes}>(use${componentName}Query.queryKey(${key}), updater, options);
39
+
40
+ use${componentName}Query.getQueryState = (${filterParams})=> queryClient.getQueryState<${responseTypes}>(use${componentName}Query.queryKey(${key}), filters);
41
+
42
+ use${componentName}Query.getQueryData = (${filterParams})=> queryClient.getQueryData<${responseTypes}>(use${componentName}Query.queryKey(${key}), filters);
43
+
44
+ use${componentName}Query.prefetch = (${params}) => queryClient.prefetchQuery<${responseTypes}>(use${componentName}Query.queryKey(${key}), ()=> use${componentName}Query.fetch(${key}));
45
+
46
+ use${componentName}Query.cancelQueries = (${params}) => queryClient.cancelQueries(use${componentName}Query.queryKey(${key}))
47
+
48
+ use${componentName}Query.invalidate = (${params}) => queryClient.invalidateQueries<${responseTypes}>(use${componentName}Query.queryKey(${key}));
49
+
50
+ use${componentName}Query.refetchStale = (${params}) => queryClient.refetchQueries<${responseTypes}>(use${componentName}Query.queryKey(${key}), { stale: true });
51
+
52
+ type ${componentName}QueryProps<T = ${responseTypes}> = ${queryParams} {
53
+ options?: UseQueryOptions<${responseTypes}, AxiosError, T, any>
54
+ }
55
+ export function use${componentName}Query<T = ${responseTypes}>({ options = {}, ...params }: ${componentName}QueryProps<T>) {
56
+ return useQuery(use${componentName}Query.queryKey(${key}), async () => use${componentName}Query.fetch(${key}), { enabled: ${enabledParam}, ...options });
57
+ }`;
58
+ const mutation = `
59
+ type ${componentName}MutationProps<T> = {
60
+ options?: UseMutationOptions<${responseTypes}, AxiosError, ${mutationParams}, T>
61
+ }
62
+ export function use${componentName}Mutation<T = ${responseTypes}>(props?: ${componentName}MutationProps<T>) {
63
+ return useMutation(async (${key}) => use${componentName}Query.fetch(${key}), props?.options)
64
+ };`;
65
+ return query + mutation;
66
+ };
67
+ /**
68
+ * Generate a react-query component from openapi operation specs
69
+ */
70
+ const createHook = ({ operation, verb, route, operationIds, parameters, schemasComponents, headerFilters, }) => {
71
+ const { operationId = route.replace('/', '') } = operation;
72
+ if (operationId === '*') {
73
+ throw new Error(`Invalid operationId/Route set for ${verb} ${route}`);
74
+ }
75
+ if (operationIds.includes(operationId)) {
76
+ throw new Error(`"${operationId}" is duplicated in your schema definition!`);
77
+ }
78
+ operationIds.push(operationId);
79
+ route = route.replace(/\{/g, '${').replace('//', '/'); // `/pet/{id}` => `/pet/${id}`
80
+ // Remove the last param of the route if we are in the DELETE case
81
+ let lastParamInTheRoute = null;
82
+ const componentName = pascal(operationId);
83
+ const isOk = ([statusCode]) => statusCode.toString().startsWith('2');
84
+ const responseTypes = getResReqTypes(Object.entries(operation.responses).filter(isOk)) || 'void';
85
+ const requestBodyTypes = getResReqTypes([['body', operation.requestBody]]);
86
+ let imports = [responseTypes];
87
+ const paramsInPath = getParamsInPath(route).filter((param) => !(verb === 'delete' && param === lastParamInTheRoute));
88
+ const { query: queryParams = [], path: pathParams = [], header = [], } = groupBy([...(parameters || []), ...(operation.parameters || [])].map((p) => {
89
+ if (isReference(p)) {
90
+ return get(schemasComponents, p.$ref.replace('#/components/', '').replace('/', '.'));
91
+ }
92
+ else {
93
+ return p;
94
+ }
95
+ }), 'in');
96
+ const headerParams = header.filter((p) => !headerFilters?.includes(p.name));
97
+ let enabled = [];
98
+ // TODO: extract all requestBody or remove useQuery variants
99
+ let enabledParam = '!!params';
100
+ [...queryParams, ...pathParams, ...headerParams].forEach((item) => {
101
+ if (item.required) {
102
+ enabled.push(`["${item.name}"]`);
103
+ if (enabledParam && enabledParam !== '!!params') {
104
+ enabledParam += `&& params['${item.name}'] != null`;
105
+ }
106
+ else {
107
+ enabledParam = `params['${item.name}'] != null`;
108
+ }
109
+ }
110
+ });
111
+ // `!props${enabled.join('== null && !props')}`;
112
+ const paramsTypes = paramsInPath
113
+ .map((p) => {
114
+ try {
115
+ const { name, required, schema } = pathParams.find((i) => i.name === p);
116
+ return `${name}${required ? '' : '?'}: ${resolveValue(schema)}`;
117
+ }
118
+ catch (err) {
119
+ throw new Error(`The path params ${p} can't be found in parameters (${operationId})`);
120
+ }
121
+ })
122
+ .join('; ');
123
+ const queryParamsType = queryParams
124
+ .map((p) => {
125
+ const processedName = IdentifierRegexp.test(p.name) ? p.name : `"${p.name}"`;
126
+ return `${formatDescription(p.description)}${processedName}${p.required ? '' : '?'}: ${resolveValue(p.schema)}`;
127
+ })
128
+ .join(';\n ');
129
+ const headerType = headerParams
130
+ .map((p) => {
131
+ try {
132
+ const { name, required, schema } = headerParams.find((i) => i.name === p.name);
133
+ return `"${name}"${required ? '' : '?'}: ${resolveValue(schema)}`;
134
+ }
135
+ catch (err) {
136
+ throw new Error(`The path params ${p} can't be found in parameters (${operationId})`);
137
+ }
138
+ })
139
+ .join('; ');
140
+ // Retrieve the type of the param for delete verb
141
+ const lastParamInTheRouteDefinition = operation.parameters && lastParamInTheRoute
142
+ ? operation.parameters.find((p) => {
143
+ if (isReference(p)) {
144
+ return false;
145
+ }
146
+ return p.name === lastParamInTheRoute;
147
+ }) // Reference is not possible
148
+ : { schema: { type: 'string' } };
149
+ if (!lastParamInTheRouteDefinition) {
150
+ throw new Error(`The path params ${lastParamInTheRoute} can't be found in parameters (${operationId})`);
151
+ }
152
+ const description = formatDescription(operation.summary && operation.description
153
+ ? `${operation.summary}\n\n${operation.description}`
154
+ : `${operation.summary || ''}${operation.description || ''}`);
155
+ let output = `\n\n${description}`;
156
+ const headerParam = headerType && headerType !== 'void' ? `${headerType};` : '';
157
+ const queryParam = queryParamsType && queryParamsType !== 'void' ? `${queryParamsType}` : '';
158
+ const requestBodyComponent = requestBodyTypes && requestBodyTypes !== 'void' ? `${requestBodyTypes}` : '';
159
+ if (requestBodyComponent) {
160
+ imports.push(requestBodyComponent);
161
+ }
162
+ // QUERIES
163
+ if (!requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
164
+ output += `
165
+ // SECTION-A
166
+ use${componentName}Query.fetch = async () => {
167
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`);
168
+ return result.data;
169
+ }
170
+ `;
171
+ output += createQueryHooks({ componentName, responseTypes, enabledParam, emptyParams: true });
172
+ }
173
+ if (!requestBodyComponent && paramsInPath.length && queryParam && !headerParam) {
174
+ output += `
175
+ // SECTION-B
176
+ type ${componentName}Params = {
177
+ ${paramsTypes}
178
+ ${queryParamsType};
179
+ }
180
+
181
+ use${componentName}Query.fetch = async (props:${componentName}Params) => {
182
+ const {${paramsInPath.join(', ')}, ...params} = props
183
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, {params})
184
+ return result.data;
185
+ }`;
186
+ output += createQueryHooks({ componentName, responseTypes, enabledParam });
187
+ }
188
+ if (!requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
189
+ output += `
190
+ // SECTION-C
191
+ type ${componentName}Params = {
192
+ ${paramsTypes}
193
+ }
194
+
195
+ use${componentName}Query.fetch = async (props: ${componentName}Params ) => {
196
+ const result = await api.${verb}<${responseTypes}>(\`${route.replace(/\{/g, '{props.')}\`);
197
+ return result.data;
198
+ }
199
+ `;
200
+ output += createQueryHooks({ componentName, responseTypes, enabledParam });
201
+ }
202
+ if (!requestBodyComponent && !paramsInPath.length && queryParam && !headerParam) {
203
+ output += `
204
+ // SECTION-D
205
+ type ${componentName}Params = {
206
+ ${queryParamsType}
207
+ }
208
+
209
+ use${componentName}Query.fetch = async (props: ${componentName}Params) => {
210
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, {params: props})
211
+ return result.data;
212
+ }
213
+ `;
214
+ output += createQueryHooks({ componentName, responseTypes, enabledParam });
215
+ }
216
+ if (requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
217
+ output += `
218
+ // SECTION-E
219
+ type ${componentName}Params = ${requestBodyComponent}
220
+
221
+ use${componentName}Query.fetch = async (body: ${componentName}Params) => {
222
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, body)
223
+ return result.data
224
+ }
225
+
226
+ `;
227
+ output += createQueryHooks({ componentName, responseTypes, enabledParam });
228
+ }
229
+ if (requestBodyComponent && !paramsInPath.length && queryParam && !headerParam) {
230
+ output += `
231
+ // SECTION-G
232
+ // TODO: LOOKS BROKEN
233
+ type ${componentName}Params = {
234
+ body: ${requestBodyComponent}
235
+ queryParams: ${queryParamsType}
236
+ }
237
+
238
+ type ${componentName}QueryProps<T = ${responseTypes}> = ${componentName}Params & {
239
+ options?: UseQueryOptions<${responseTypes}, AxiosError, T, any>
240
+ }
241
+
242
+ use${componentName}Query.fetch = async ({body, queryParams}: ${componentName}Params) => {
243
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, body, {params: queryParams})
244
+ return result.data
245
+ }
246
+ `;
247
+ output += createQueryHooks({ componentName, responseTypes, enabledParam });
248
+ }
249
+ if (!requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
250
+ output += `
251
+ // SECTION-H
252
+ type ${componentName}Params = {
253
+ ${headerParam}
254
+ };
255
+
256
+ use${componentName}Query.fetch = async (headers: ${componentName}Params) => {
257
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, {headers});
258
+ return result.data;
259
+ }
260
+ `;
261
+ output += createQueryHooks({ componentName, responseTypes, enabledParam });
262
+ }
263
+ if (requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
264
+ output += `
265
+ // SECTION-J
266
+ type ${componentName}Params = {
267
+ body: ${requestBodyComponent}
268
+ headers: {${headerParam}}
269
+ };
270
+
271
+ use${componentName}Query.fetch = async ({headers, body}: ${componentName}Params) => {
272
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, body, {headers})
273
+ return result.data
274
+ }`;
275
+ output += createQueryHooks({ componentName, responseTypes, enabledParam });
276
+ }
277
+ if (!requestBodyComponent && !paramsInPath.length && queryParam && headerParam) {
278
+ output += `
279
+ // SECTION-K
280
+ type ${componentName}Params = {
281
+ headers: {${headerParam}}
282
+ queryParams: {${queryParamsType} }
283
+ }
284
+ use${componentName}Query.fetch = async ({headers, queryParams}: ${componentName}Params) => {
285
+ const result = await api.${verb}<${responseTypes}>(\`${route}\`, body, {headers, params: queryParams})
286
+ return result.data
287
+ }`;
288
+ output += createQueryHooks({ componentName, responseTypes, enabledParam });
289
+ }
290
+ if (requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
291
+ output += `// TODO: NOT SUPPORTED requestBodyComponent && paramsInPath)`;
292
+ }
293
+ if (requestBodyComponent && paramsInPath.length && queryParam && !headerParam) {
294
+ output += `// TODO: NOT SUPPORTED requestBodyComponent && paramsInPath && queryParam)`;
295
+ }
296
+ if (requestBodyComponent && !paramsInPath.length && queryParam && headerParam) {
297
+ output += `// TODO: NOT SUPPORTED requestBodyComponent && queryParam && headerParam)`;
298
+ }
299
+ if (requestBodyComponent && paramsInPath.length && queryParam && headerParam) {
300
+ output += `// TODO: NOT SUPPORTED requestBodyComponent && paramsInPath && queryParam && headerParam)`;
301
+ }
302
+ if (!requestBodyComponent && paramsInPath.length && !queryParam && headerParam) {
303
+ output += `// TODO: NOT SUPPORTED (paramsInPath && headerParam)`;
304
+ }
305
+ if (!requestBodyComponent && paramsInPath.length && queryParam && headerParam) {
306
+ output += `// TODO: NOT SUPPORTED (paramsInPath && queryParam && headerParam)`;
307
+ }
308
+ if (requestBodyComponent && paramsInPath.length && !queryParam && headerParam) {
309
+ output += `// TODO: NOT SUPPORTED (requestBodyComponent && paramsInPath && headerParam)`;
310
+ }
311
+ return { implementation: output, imports };
312
+ };
313
+ export const generateImports = ({ schemaName, apiDirectory, queryClientDir, schemaImports, }) => {
314
+ const importTypes = schemaImports.join(',');
315
+ return `
316
+ import {
317
+ useQuery,
318
+ useMutation,
319
+ UseQueryOptions,
320
+ UseMutationOptions,
321
+ QueryKey,
322
+ SetDataOptions,
323
+ QueryFilters
324
+ } from '@tanstack/react-query';
325
+
326
+ import { AxiosError } from 'axios';
327
+ import { api } from '${apiDirectory}';
328
+ import { queryClient } from '${queryClientDir}';
329
+
330
+ import {${importTypes}} from './${schemaName}'
331
+
332
+ type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput);
333
+ `;
334
+ };
335
+ export const generateQueryHooks = ({ spec, operationIds, headerFilters, }) => {
336
+ const { paths, components } = spec;
337
+ let hooks = '';
338
+ let schemaImports = [];
339
+ Object.entries(paths).forEach(([route, verbs]) => {
340
+ Object.entries(verbs).forEach(([verb, operation]) => {
341
+ if (['get', 'post', 'patch', 'put', 'delete'].includes(verb) && !operation.deprecated) {
342
+ const { implementation, imports } = createHook({
343
+ operation,
344
+ verb,
345
+ route: spec.basePath + route,
346
+ operationIds,
347
+ parameters: verbs.parameters,
348
+ schemasComponents: components,
349
+ headerFilters,
350
+ });
351
+ hooks += implementation;
352
+ imports.forEach((element) => {
353
+ schemaImports.push(element.replace('[]', ''));
354
+ });
355
+ }
356
+ });
357
+ });
358
+ const schemaImportsFiltered = schemaImports.filter((item) => !!item && item !== 'void' && item !== 'boolean' && item !== 'undefined' && item !== 'string');
359
+ return { implementation: hooks, schemaImports: uniq(schemaImportsFiltered) };
360
+ };
@@ -0,0 +1,22 @@
1
+ export const generateImports = ({ schemaName, apiDirectory, queryClientDir, schemaImports, }) => {
2
+ const importTypes = schemaImports.join(',');
3
+ return `
4
+ import {
5
+ useQuery,
6
+ useMutation,
7
+ UseQueryOptions,
8
+ UseMutationOptions,
9
+ QueryKey,
10
+ SetDataOptions,
11
+ QueryFilters
12
+ } from '@tanstack/react-query';
13
+
14
+ import { AxiosError } from 'axios';
15
+ import { api } from '${apiDirectory}';
16
+ import { queryClient } from '${queryClientDir}';
17
+
18
+ import {${importTypes}} from './${schemaName}'
19
+
20
+ type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput);
21
+ `;
22
+ };
@@ -0,0 +1,97 @@
1
+ import pasCase from 'case';
2
+ import lodash from 'lodash';
3
+ const { isEmpty } = lodash;
4
+ const { pascal } = pasCase;
5
+ import { formatDescription, getScalar, isReference, resolveValue } from './utils.js';
6
+ import { getDocs, getResReqTypes } from './utils.js';
7
+ /**
8
+ * Generate the interface string
9
+ */
10
+ const generateInterface = (name, schema) => {
11
+ const scalar = getScalar(schema);
12
+ return `
13
+ ${formatDescription(schema.description)}
14
+ export type ${pascal(name)} = ${scalar}
15
+ `;
16
+ };
17
+ /**
18
+ * Extract all types from #/components/schemas
19
+ */
20
+ const generateSchemasDefinition = (schemas = {}) => {
21
+ if (isEmpty(schemas)) {
22
+ return '';
23
+ }
24
+ return ('\n // SCEHMAS \n' +
25
+ Object.entries(schemas)
26
+ .map(([name, schema]) => !isReference(schema) &&
27
+ (!schema.type || schema.type === 'object') &&
28
+ !schema.allOf &&
29
+ !schema.oneOf &&
30
+ !isReference(schema) &&
31
+ !schema.nullable
32
+ ? generateInterface(name, schema)
33
+ : `${formatDescription(isReference(schema) ? undefined : schema.description)} export type ${pascal(name)} = ${resolveValue(schema)};`)
34
+ .join('\n\n') +
35
+ '\n');
36
+ };
37
+ /**
38
+ * Extract all types from #/components/requestBodies
39
+ */
40
+ const generateRequestBodiesDefinition = (requestBodies = {}) => {
41
+ if (isEmpty(requestBodies)) {
42
+ return '';
43
+ }
44
+ return ('\n // REQUEST BODIES \n' +
45
+ Object.entries(requestBodies)
46
+ .map(([name, requestBody]) => {
47
+ const doc = getDocs(requestBody);
48
+ const type = getResReqTypes([['', requestBody]]);
49
+ const isEmptyInterface = type === '{}';
50
+ if (isEmptyInterface) {
51
+ return `${doc}export type ${pascal(name)}RequestBody = ${type}`;
52
+ }
53
+ else if (type.includes('{') && !type.includes('|') && !type.includes('&')) {
54
+ return `${doc}export type ${pascal(name)}RequestBody = ${type}`;
55
+ }
56
+ else {
57
+ return `${doc}export type ${pascal(name)}RequestBody = ${type};`;
58
+ }
59
+ })
60
+ .join('\n\n') +
61
+ '\n');
62
+ };
63
+ /**
64
+ * Extract all types from #/components/responses
65
+ */
66
+ const generateResponsesDefinition = (responses = {}) => {
67
+ if (isEmpty(responses)) {
68
+ return '';
69
+ }
70
+ return ('\n // RESPONSES \n' +
71
+ Object.entries(responses)
72
+ .map(([name, response]) => {
73
+ const doc = getDocs(response);
74
+ const type = getResReqTypes([['', response]]);
75
+ const isEmptyInterface = type === '{}';
76
+ if (isEmptyInterface) {
77
+ return `export type RQ${pascal(name)}Response = ${type}`;
78
+ }
79
+ else if (type.includes('{') && !type.includes('|') && !type.includes('&')) {
80
+ return `${doc}export type RQ${pascal(name)}Response = ${type}`;
81
+ }
82
+ else {
83
+ return `${doc}export type RQ${pascal(name)}Response = ${type};`;
84
+ }
85
+ })
86
+ .join('\n\n') +
87
+ '\n');
88
+ };
89
+ /**
90
+ * Extract all types from #/components/schemas
91
+ */
92
+ export const generateSchemas = ({ spec }) => {
93
+ const schemaOutput = generateSchemasDefinition(spec.components?.schemas) +
94
+ generateResponsesDefinition(spec.components?.responses) +
95
+ generateRequestBodiesDefinition(spec.components?.requestBodies);
96
+ return schemaOutput;
97
+ };