react-query-lightbase-codegen 0.5.0 → 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.
- package/README.md +76 -0
- package/package.json +36 -4
- package/lib/cjs/convertSwaggerFile.js +0 -32
- package/lib/cjs/generateHooks.js +0 -401
- package/lib/cjs/generateImports.js +0 -31
- package/lib/cjs/generateRequestBodiesDefinition.js +0 -36
- package/lib/cjs/generateResponsesDefinition.js +0 -36
- package/lib/cjs/generateSchemas.js +0 -103
- package/lib/cjs/generateSchemasDefinition.js +0 -40
- package/lib/cjs/getResReqTypes.js +0 -162
- package/lib/cjs/import-open-api.js +0 -39
- package/lib/cjs/importSpecs.js +0 -87
- package/lib/cjs/index.js +0 -7
- package/lib/cjs/react-query-codegen-import.js +0 -49
- package/lib/cjs/resolveDiscriminator.js +0 -31
- package/lib/cjs/types.js +0 -2
- package/lib/cjs/utils.js +0 -168
- package/lib/esm/convertSwaggerFile.js +0 -25
- package/lib/esm/generateHooks.js +0 -394
- package/lib/esm/generateImports.js +0 -27
- package/lib/esm/generateRequestBodiesDefinition.js +0 -29
- package/lib/esm/generateResponsesDefinition.js +0 -29
- package/lib/esm/generateSchemas.js +0 -96
- package/lib/esm/generateSchemasDefinition.js +0 -33
- package/lib/esm/getResReqTypes.js +0 -150
- package/lib/esm/import-open-api.js +0 -32
- package/lib/esm/importSpecs.js +0 -80
- package/lib/esm/index.js +0 -3
- package/lib/esm/react-query-codegen-import.js +0 -42
- package/lib/esm/resolveDiscriminator.js +0 -24
- package/lib/esm/types.js +0 -1
- package/lib/esm/utils.js +0 -156
package/lib/cjs/utils.js
DELETED
|
@@ -1,168 +0,0 @@
|
|
|
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
|
-
}
|
|
138
|
-
return `\n/**\n${description
|
|
139
|
-
.split('\n')
|
|
140
|
-
.map((i) => `* ${i}`)
|
|
141
|
-
.join('\n')}\n */`;
|
|
142
|
-
};
|
|
143
|
-
exports.formatDescription = formatDescription;
|
|
144
|
-
/**
|
|
145
|
-
* Extract responses / request types from open-api specs
|
|
146
|
-
*/
|
|
147
|
-
const getResReqTypes = (responsesOrRequests) => {
|
|
148
|
-
return uniq(responsesOrRequests.map(([_, res]) => {
|
|
149
|
-
if (!res) {
|
|
150
|
-
return;
|
|
151
|
-
}
|
|
152
|
-
if ((0, exports.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 (0, exports.resolveValue)(schema);
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
|
-
return;
|
|
164
|
-
}
|
|
165
|
-
return;
|
|
166
|
-
})).join(' | ');
|
|
167
|
-
};
|
|
168
|
-
exports.getResReqTypes = getResReqTypes;
|
|
@@ -1,25 +0,0 @@
|
|
|
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
|
-
};
|
package/lib/esm/generateHooks.js
DELETED
|
@@ -1,394 +0,0 @@
|
|
|
1
|
-
import lodash from 'lodash';
|
|
2
|
-
const { get, groupBy } = lodash;
|
|
3
|
-
import { formatDescription, getResReqTypes, isReference, resolveValue } from './utils.js';
|
|
4
|
-
import pasCase from 'case';
|
|
5
|
-
import chalk from 'chalk';
|
|
6
|
-
const { pascal, camel } = pasCase;
|
|
7
|
-
const IdentifierRegexp = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
|
|
8
|
-
/**
|
|
9
|
-
* Return every params in a path
|
|
10
|
-
*/
|
|
11
|
-
const getParamsInPath = (path) => {
|
|
12
|
-
let n;
|
|
13
|
-
const output = [];
|
|
14
|
-
const templatePathRegex = /\{(\w+)}/g;
|
|
15
|
-
while ((n = templatePathRegex.exec(path)) !== null) {
|
|
16
|
-
output.push(n[1]);
|
|
17
|
-
}
|
|
18
|
-
return output;
|
|
19
|
-
};
|
|
20
|
-
/**
|
|
21
|
-
* Generate a react-query component from openapi operation specs
|
|
22
|
-
*/
|
|
23
|
-
export const createHook = ({ operation, verb, route, operationIds, parameters, schemasComponents, headerFilters, overrides, }) => {
|
|
24
|
-
const { operationId = route.replace('/', '') } = operation;
|
|
25
|
-
if (operationId === '*') {
|
|
26
|
-
throw new Error(`Invalid operationId/Route set for ${verb} ${route}`);
|
|
27
|
-
}
|
|
28
|
-
if (operationIds.includes(operationId)) {
|
|
29
|
-
return { implementation: '', imports: [], queryImports: [] };
|
|
30
|
-
}
|
|
31
|
-
operationIds.push(operationId);
|
|
32
|
-
route = route.replace(/\{/g, '${').replace('//', '/'); // `/pet/{id}` => `/pet/${id}`
|
|
33
|
-
// Remove the last param of the route if we are in the DELETE case
|
|
34
|
-
let lastParamInTheRoute = null;
|
|
35
|
-
const componentName = pascal(operationId);
|
|
36
|
-
const isOk = ([statusCode]) => statusCode.toString().startsWith('2');
|
|
37
|
-
const responseTypes = getResReqTypes(Object.entries(operation.responses).filter(isOk)) || 'void';
|
|
38
|
-
const requestBodyTypes = getResReqTypes([['body', operation.requestBody]]);
|
|
39
|
-
let imports = [responseTypes];
|
|
40
|
-
let queryImports = [];
|
|
41
|
-
const paramsInPath = getParamsInPath(route).filter((param) => !(verb === 'delete' && param === lastParamInTheRoute));
|
|
42
|
-
const { query: queryParams = [], path: pathParams = [], header = [], } = groupBy([...(parameters || []), ...(operation.parameters || [])].map((p) => {
|
|
43
|
-
if (isReference(p)) {
|
|
44
|
-
return get(schemasComponents, p.$ref.replace('#/components/', '').replace('/', '.'));
|
|
45
|
-
}
|
|
46
|
-
else {
|
|
47
|
-
return p;
|
|
48
|
-
}
|
|
49
|
-
}), 'in');
|
|
50
|
-
const headerParams = header.filter((p) => !headerFilters?.includes(p.name));
|
|
51
|
-
let enabled = [];
|
|
52
|
-
// TODO: extract all requestBody or remove useQuery variants
|
|
53
|
-
let enabledParam = '!!params';
|
|
54
|
-
[...queryParams, ...pathParams, ...headerParams].forEach((item) => {
|
|
55
|
-
if (item.required) {
|
|
56
|
-
enabled.push(`["${item.name}"]`);
|
|
57
|
-
if (enabledParam && enabledParam !== '!!params') {
|
|
58
|
-
enabledParam += `&& params['${item.name}'] != null`;
|
|
59
|
-
}
|
|
60
|
-
else {
|
|
61
|
-
enabledParam = `params['${item.name}'] != null`;
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
});
|
|
65
|
-
// `!props${enabled.join('== null && !props')}`;
|
|
66
|
-
const paramsTypes = paramsInPath
|
|
67
|
-
.map((p) => {
|
|
68
|
-
try {
|
|
69
|
-
const { name, required, schema } = pathParams.find((i) => i.name === p);
|
|
70
|
-
return `${name}${required ? '' : '?'}: ${resolveValue(schema)}`;
|
|
71
|
-
}
|
|
72
|
-
catch (err) {
|
|
73
|
-
throw new Error(`The path params ${p} can't be found in parameters (${operationId})`);
|
|
74
|
-
}
|
|
75
|
-
})
|
|
76
|
-
.join('; ');
|
|
77
|
-
const queryParamsType = queryParams
|
|
78
|
-
.map((p) => {
|
|
79
|
-
const processedName = IdentifierRegexp.test(p.name) ? p.name : `"${p.name}"`;
|
|
80
|
-
return `${formatDescription(p.description)}
|
|
81
|
-
${processedName}${p.required ? '' : '?'}: ${resolveValue(p.schema)}`;
|
|
82
|
-
})
|
|
83
|
-
.join(';\n ');
|
|
84
|
-
const headerType = headerParams
|
|
85
|
-
.map((p) => {
|
|
86
|
-
try {
|
|
87
|
-
const { name, required, schema } = headerParams.find((i) => i.name === p.name);
|
|
88
|
-
return `"${name}"${required ? '' : '?'}: ${resolveValue(schema)}`;
|
|
89
|
-
}
|
|
90
|
-
catch (err) {
|
|
91
|
-
throw new Error(`The path params ${p} can't be found in parameters (${operationId})`);
|
|
92
|
-
}
|
|
93
|
-
})
|
|
94
|
-
.join('; ');
|
|
95
|
-
// Retrieve the type of the param for delete verb
|
|
96
|
-
const lastParamInTheRouteDefinition = operation.parameters && lastParamInTheRoute
|
|
97
|
-
? operation.parameters.find((p) => {
|
|
98
|
-
if (isReference(p)) {
|
|
99
|
-
return false;
|
|
100
|
-
}
|
|
101
|
-
return p.name === lastParamInTheRoute;
|
|
102
|
-
}) // Reference is not possible
|
|
103
|
-
: { schema: { type: 'string' } };
|
|
104
|
-
if (!lastParamInTheRouteDefinition) {
|
|
105
|
-
throw new Error(`The path params ${lastParamInTheRoute} can't be found in parameters (${operationId})`);
|
|
106
|
-
}
|
|
107
|
-
const defaultDescription = `type: ${verb}\noperationId: ${operationId}\nurl: ${route}`;
|
|
108
|
-
const description = formatDescription(operation.summary && operation.description
|
|
109
|
-
? `${defaultDescription}\n\n${operation.summary}\n\n${operation.description}`
|
|
110
|
-
: `${defaultDescription}`);
|
|
111
|
-
let output = `\n\n${description}`;
|
|
112
|
-
const headerParam = headerType && headerType !== 'void' ? `${headerType};` : '';
|
|
113
|
-
const queryParam = queryParamsType && queryParamsType !== 'void' ? `${queryParamsType}` : '';
|
|
114
|
-
const requestBodyComponent = requestBodyTypes && requestBodyTypes !== 'void' ? `${requestBodyTypes}` : '';
|
|
115
|
-
if (requestBodyComponent) {
|
|
116
|
-
imports.push(requestBodyComponent);
|
|
117
|
-
}
|
|
118
|
-
const isUpdateRequest = ['post', 'patch', 'put'].includes(verb);
|
|
119
|
-
const generateProps = (props) => {
|
|
120
|
-
return props.map((item) => `["${item.name}"]: props["${item.name}"]`).join(',');
|
|
121
|
-
};
|
|
122
|
-
const generateBodyProps = () => {
|
|
123
|
-
const definitionKey = Object.keys(schemasComponents?.schemas || {}).find((key) => pascal(key) === requestBodyComponent);
|
|
124
|
-
if (definitionKey) {
|
|
125
|
-
const scheme = schemasComponents?.schemas?.[definitionKey];
|
|
126
|
-
return Object.keys(scheme.properties)
|
|
127
|
-
.map((item) => `["${item}"]: props["${item}"]`)
|
|
128
|
-
.join(',');
|
|
129
|
-
}
|
|
130
|
-
};
|
|
131
|
-
const fetchName = camel(componentName);
|
|
132
|
-
const createQueryHooks = (emptyParams) => {
|
|
133
|
-
const params = emptyParams ? '' : `params: ${componentName}Params,`;
|
|
134
|
-
const key = emptyParams ? '' : `params`;
|
|
135
|
-
const mutationParams = emptyParams ? 'void' : `${componentName}Params`;
|
|
136
|
-
const queryParamType = emptyParams ? '' : `${componentName}Params &`;
|
|
137
|
-
const filterParams = emptyParams
|
|
138
|
-
? '{ filters }: { filters?: QueryFilters }'
|
|
139
|
-
: `{ params, filters }: { params: ${componentName}Params, filters?: QueryFilters }`;
|
|
140
|
-
const cacheParams = emptyParams
|
|
141
|
-
? `{updater, options}: {updater: Updater<${responseTypes} | undefined, ${responseTypes} | undefined>, options?: SetDataOptions | undefined}`
|
|
142
|
-
: `{params, updater, options}: {params: ${componentName}Params, updater: Updater<${responseTypes} | undefined, ${responseTypes} | undefined>, options?: SetDataOptions | undefined}`;
|
|
143
|
-
const queryKey = emptyParams
|
|
144
|
-
? `use${componentName}Query.baseKey()`
|
|
145
|
-
: `[...use${componentName}Query.baseKey(), params]`;
|
|
146
|
-
const createQuery = () => `
|
|
147
|
-
type ${componentName}QueryProps<T = ${responseTypes}> = ${queryParamType} {
|
|
148
|
-
options?: UseQueryOptions<${responseTypes}, AxiosError, T, any>
|
|
149
|
-
}
|
|
150
|
-
export function use${componentName}Query<T = ${responseTypes}>({ options = {}, ...params }: ${componentName}QueryProps<T>) {
|
|
151
|
-
return useQuery(use${componentName}Query.queryKey(${key}), async () => ${fetchName}(${key}), { enabled: ${enabledParam}, ...options });
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
|
|
155
|
-
|
|
156
|
-
use${componentName}Query.queryKey = (${params}): QueryKey => ${queryKey};
|
|
157
|
-
|
|
158
|
-
use${componentName}Query.updateCache = (${cacheParams}) => queryClient.setQueryData<${responseTypes}>(use${componentName}Query.queryKey(${key}), updater, options);
|
|
159
|
-
|
|
160
|
-
use${componentName}Query.getQueryState = (${filterParams})=> queryClient.getQueryState<${responseTypes}>(use${componentName}Query.queryKey(${key}), filters);
|
|
161
|
-
|
|
162
|
-
use${componentName}Query.getQueryData = (${filterParams})=> queryClient.getQueryData<${responseTypes}>(use${componentName}Query.queryKey(${key}), filters);
|
|
163
|
-
|
|
164
|
-
use${componentName}Query.prefetch = (${params}) => queryClient.prefetchQuery<${responseTypes}>(use${componentName}Query.queryKey(${key}), ()=> ${fetchName}(${key}));
|
|
165
|
-
|
|
166
|
-
use${componentName}Query.cancelQueries = (${params}) => queryClient.cancelQueries(use${componentName}Query.queryKey(${key}))
|
|
167
|
-
|
|
168
|
-
use${componentName}Query.invalidate = (${params}) => queryClient.invalidateQueries<${responseTypes}>(use${componentName}Query.queryKey(${key}));
|
|
169
|
-
|
|
170
|
-
use${componentName}Query.refetchStale = (${params}) => queryClient.refetchQueries<${responseTypes}>(use${componentName}Query.queryKey(${key}), { stale: true });
|
|
171
|
-
`;
|
|
172
|
-
const getInfiniteQuery = ({ pageParam }) => `
|
|
173
|
-
type ${componentName}QueryProps<T = ${responseTypes}> = ${queryParamType} {
|
|
174
|
-
options: UseInfiniteQueryOptions<${responseTypes}, AxiosError, T, any>
|
|
175
|
-
}
|
|
176
|
-
export function use${componentName}Query<T = ${responseTypes}>({ options = {}, ...params }: ${componentName}QueryProps<T>) {
|
|
177
|
-
return useInfiniteQuery(use${componentName}Query.queryKey(${key}), async ({ pageParam = 0 }) => ${fetchName}({${pageParam}: pageParam, ...params}), { enabled: ${enabledParam}, ...options });
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
use${componentName}Query.baseKey = (): QueryKey => ["${componentName.toLowerCase()}"];
|
|
181
|
-
|
|
182
|
-
use${componentName}Query.queryKey = (${params}): QueryKey => ${queryKey};
|
|
183
|
-
|
|
184
|
-
`;
|
|
185
|
-
const createMutation = () => `
|
|
186
|
-
type ${componentName}MutationProps<T> = {
|
|
187
|
-
options?: UseMutationOptions<${responseTypes}, AxiosError, ${mutationParams}, T>
|
|
188
|
-
}
|
|
189
|
-
export function use${componentName}Mutation<T = ${responseTypes}>(props?: ${componentName}MutationProps<T>) {
|
|
190
|
-
return useMutation(async (${key}) => ${fetchName}(${key}), props?.options)
|
|
191
|
-
};
|
|
192
|
-
`;
|
|
193
|
-
const override = overrides?.[operationId];
|
|
194
|
-
if (override?.type === 'query') {
|
|
195
|
-
console.log(chalk.blue(`⚙️ [${operationId}] has been changed to a useQuery hook`));
|
|
196
|
-
queryImports.push('query');
|
|
197
|
-
return createQuery();
|
|
198
|
-
}
|
|
199
|
-
if (override?.type === 'mutation') {
|
|
200
|
-
queryImports.push('mutation');
|
|
201
|
-
console.log(chalk.blue(`⚙️ [${operationId}] has been changed to a useMutation hook`));
|
|
202
|
-
return createMutation();
|
|
203
|
-
}
|
|
204
|
-
if (override?.type === 'infiniteQuery') {
|
|
205
|
-
console.log(chalk.blue(`⚙️ [${operationId}] has been changed to a useInfiniteQuery hook`));
|
|
206
|
-
queryImports.push('infiniteQuery');
|
|
207
|
-
return getInfiniteQuery({ pageParam: override.infiniteQueryParm });
|
|
208
|
-
}
|
|
209
|
-
if (verb === 'get') {
|
|
210
|
-
queryImports.push('query');
|
|
211
|
-
return createQuery();
|
|
212
|
-
}
|
|
213
|
-
queryImports.push('mutation');
|
|
214
|
-
return createMutation();
|
|
215
|
-
};
|
|
216
|
-
output += createQueryHooks(!requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam);
|
|
217
|
-
if (!requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
|
|
218
|
-
output += `
|
|
219
|
-
const ${fetchName} = async () => {
|
|
220
|
-
const result = await api.${verb}<${responseTypes}>(\`${route}\`);
|
|
221
|
-
return result.data;
|
|
222
|
-
}
|
|
223
|
-
`;
|
|
224
|
-
}
|
|
225
|
-
if (!requestBodyComponent && paramsInPath.length && queryParam && !headerParam) {
|
|
226
|
-
const config = isUpdateRequest ? 'body,{params}' : '{params}';
|
|
227
|
-
output += `
|
|
228
|
-
type ${componentName}Params = {
|
|
229
|
-
${paramsTypes}
|
|
230
|
-
${queryParamsType};
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
const ${fetchName} = async (props:${componentName}Params) => {
|
|
234
|
-
const {${paramsInPath.join(', ')}, ...params} = props
|
|
235
|
-
const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config})
|
|
236
|
-
return result.data;
|
|
237
|
-
}`;
|
|
238
|
-
}
|
|
239
|
-
if (!requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
|
|
240
|
-
output += `
|
|
241
|
-
type ${componentName}Params = {
|
|
242
|
-
${paramsTypes}
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
const ${fetchName} = async (props: ${componentName}Params ) => {
|
|
246
|
-
const result = await api.${verb}<${responseTypes}>(\`${route.replace(/\{/g, '{props.')}\`);
|
|
247
|
-
return result.data;
|
|
248
|
-
}
|
|
249
|
-
`;
|
|
250
|
-
}
|
|
251
|
-
if (!requestBodyComponent && !paramsInPath.length && queryParam && !headerParam) {
|
|
252
|
-
const config = isUpdateRequest ? 'null,{params}' : '{params}';
|
|
253
|
-
output += `
|
|
254
|
-
type ${componentName}Params = {
|
|
255
|
-
${queryParamsType}
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
const ${fetchName} = async (params: ${componentName}Params) => {
|
|
259
|
-
const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config})
|
|
260
|
-
return result.data;
|
|
261
|
-
}
|
|
262
|
-
`;
|
|
263
|
-
}
|
|
264
|
-
if (!requestBodyComponent && !paramsInPath.length && queryParam && headerParam) {
|
|
265
|
-
const config = isUpdateRequest ? 'null,{headers, params: queryParams}' : '{headers, params: queryParams}';
|
|
266
|
-
output += `
|
|
267
|
-
type ${componentName}Params = {
|
|
268
|
-
${headerParam}
|
|
269
|
-
${queryParamsType}
|
|
270
|
-
}
|
|
271
|
-
const ${fetchName} = async (props: ${componentName}Params) => {
|
|
272
|
-
const headers = {${generateProps(header)}}
|
|
273
|
-
const queryParams = {${generateProps(queryParams)}}
|
|
274
|
-
const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config})
|
|
275
|
-
return result.data
|
|
276
|
-
}`;
|
|
277
|
-
}
|
|
278
|
-
if (!requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
|
|
279
|
-
const config = isUpdateRequest ? 'null,{headers}' : '{headers}';
|
|
280
|
-
output += `
|
|
281
|
-
type ${componentName}Params = {
|
|
282
|
-
${headerParam}
|
|
283
|
-
};
|
|
284
|
-
|
|
285
|
-
const ${fetchName} = async (headers: ${componentName}Params) => {
|
|
286
|
-
const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config});
|
|
287
|
-
return result.data;
|
|
288
|
-
}
|
|
289
|
-
`;
|
|
290
|
-
}
|
|
291
|
-
if (requestBodyComponent && !paramsInPath.length && !queryParam && !headerParam) {
|
|
292
|
-
output += `
|
|
293
|
-
type ${componentName}Params = ${requestBodyComponent}
|
|
294
|
-
|
|
295
|
-
const ${fetchName} = async (body: ${componentName}Params) => {
|
|
296
|
-
const result = await api.${verb}<${responseTypes}>(\`${route}\`, body)
|
|
297
|
-
return result.data
|
|
298
|
-
}
|
|
299
|
-
`;
|
|
300
|
-
}
|
|
301
|
-
if (requestBodyComponent && !paramsInPath.length && queryParam && !headerParam) {
|
|
302
|
-
const config = isUpdateRequest ? 'null,{headers, params: queryParams}' : '{headers, params: queryParams}';
|
|
303
|
-
const queryParamsProps = queryParams.map((item) => `["${item.name}"]: props["${item.name}"]`);
|
|
304
|
-
output += `
|
|
305
|
-
type ${componentName}Params = ${requestBodyComponent} & {
|
|
306
|
-
${queryParamsType}
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
type ${componentName}QueryProps<T = ${responseTypes}> = ${componentName}Params & {
|
|
310
|
-
const body = {${generateBodyProps()}}
|
|
311
|
-
const params = {${generateProps(queryParams)}}
|
|
312
|
-
options?: UseQueryOptions<${responseTypes}, AxiosError, T, any>
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
const ${fetchName} = async ({body, params}: ${componentName}Params) => {
|
|
316
|
-
const queryParams = {${queryParamsProps.join(',')}}
|
|
317
|
-
const result = await api.${verb}<${responseTypes}>(\`${route}\`, ${config})
|
|
318
|
-
return result.data
|
|
319
|
-
}
|
|
320
|
-
`;
|
|
321
|
-
}
|
|
322
|
-
if (requestBodyComponent && !paramsInPath.length && !queryParam && headerParam) {
|
|
323
|
-
output += `
|
|
324
|
-
type ${componentName}Params = ${requestBodyComponent} & {
|
|
325
|
-
${headerParam}
|
|
326
|
-
};
|
|
327
|
-
|
|
328
|
-
const ${fetchName} = async (props: ${componentName}Params) => {
|
|
329
|
-
const headers = {${generateProps(header)}}
|
|
330
|
-
const body = {${generateBodyProps()}}
|
|
331
|
-
const result = await api.${verb}<${responseTypes}>(\`${route}\`, body, {headers})
|
|
332
|
-
return result.data
|
|
333
|
-
}
|
|
334
|
-
`;
|
|
335
|
-
}
|
|
336
|
-
if (requestBodyComponent && !paramsInPath.length && queryParam && headerParam) {
|
|
337
|
-
output += `
|
|
338
|
-
type ${componentName}Params = ${requestBodyComponent} & {
|
|
339
|
-
${headerParam}
|
|
340
|
-
${paramsTypes}
|
|
341
|
-
};
|
|
342
|
-
|
|
343
|
-
const ${fetchName} = async (props: ${componentName}Params) => {
|
|
344
|
-
const body = {${generateBodyProps()}}
|
|
345
|
-
const headers = {${generateProps(header)}}
|
|
346
|
-
const params = {${generateProps(queryParams)}}
|
|
347
|
-
const result = await api.${verb}<${responseTypes}>(\`${route}\`, body, {headers, params})
|
|
348
|
-
return result.data
|
|
349
|
-
}
|
|
350
|
-
`;
|
|
351
|
-
}
|
|
352
|
-
if (requestBodyComponent && paramsInPath.length && !queryParam && !headerParam) {
|
|
353
|
-
output += `
|
|
354
|
-
type ${componentName}Params = ${requestBodyComponent} & {
|
|
355
|
-
${headerParam}
|
|
356
|
-
${paramsTypes}
|
|
357
|
-
};
|
|
358
|
-
|
|
359
|
-
const ${fetchName} = async (props: ${componentName}Params) => {
|
|
360
|
-
const body = {${generateBodyProps()}}
|
|
361
|
-
const result = await api.${verb}<${responseTypes}>(\`${route.replace(/\{/g, '{props.')}\`, body)
|
|
362
|
-
return result.data
|
|
363
|
-
}
|
|
364
|
-
`;
|
|
365
|
-
}
|
|
366
|
-
if (requestBodyComponent && paramsInPath.length && queryParam && !headerParam) {
|
|
367
|
-
output += `// TODO: NOT SUPPORTED requestBodyComponent && paramsInPath && queryParam)`;
|
|
368
|
-
}
|
|
369
|
-
if (requestBodyComponent && paramsInPath.length && queryParam && headerParam) {
|
|
370
|
-
output += `// TODO: NOT SUPPORTED requestBodyComponent && paramsInPath && queryParam && headerParam)`;
|
|
371
|
-
}
|
|
372
|
-
if (!requestBodyComponent && paramsInPath.length && !queryParam && headerParam) {
|
|
373
|
-
const config = isUpdateRequest ? 'null,{headers}' : '{headers}';
|
|
374
|
-
output += `
|
|
375
|
-
type ${componentName}Params = {
|
|
376
|
-
${headerParam}
|
|
377
|
-
${paramsTypes}
|
|
378
|
-
};
|
|
379
|
-
|
|
380
|
-
const ${fetchName} = async (props: ${componentName}Params) => {
|
|
381
|
-
const headers = {${generateProps(header)}}
|
|
382
|
-
const result = await api.${verb}<${responseTypes}>(\`${route.replace(/\{/g, '{props.')}\`, ${config})
|
|
383
|
-
return result.data
|
|
384
|
-
}
|
|
385
|
-
`;
|
|
386
|
-
}
|
|
387
|
-
if (!requestBodyComponent && paramsInPath.length && queryParam && headerParam) {
|
|
388
|
-
output += `// TODO: NOT SUPPORTED (paramsInPath && queryParam && headerParam)`;
|
|
389
|
-
}
|
|
390
|
-
if (requestBodyComponent && paramsInPath.length && !queryParam && headerParam) {
|
|
391
|
-
output += `// TODO: NOT SUPPORTED (requestBodyComponent && paramsInPath && headerParam)`;
|
|
392
|
-
}
|
|
393
|
-
return { implementation: output, imports, queryImports };
|
|
394
|
-
};
|
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
export const generateImports = ({ schemaName, apiDirectory, queryClientDir, schemaImports, queryImports, }) => {
|
|
2
|
-
const importTypes = schemaImports.join(',');
|
|
3
|
-
let imports = [];
|
|
4
|
-
if (queryImports.includes('query')) {
|
|
5
|
-
imports = [...imports, 'useQuery', 'UseQueryOptions', 'QueryKey', 'SetDataOptions', 'QueryFilters'];
|
|
6
|
-
}
|
|
7
|
-
if (queryImports.includes('infiniteQuery')) {
|
|
8
|
-
imports = [...imports, 'useInfiniteQuery', 'UseInfiniteQueryOptions', 'QueryKey'];
|
|
9
|
-
}
|
|
10
|
-
if (queryImports.includes('mutation')) {
|
|
11
|
-
imports = [...imports, 'UseMutationOptions', 'useMutation'];
|
|
12
|
-
}
|
|
13
|
-
const importString = [...new Set(imports)].join(',');
|
|
14
|
-
return `
|
|
15
|
-
import {
|
|
16
|
-
${importString}
|
|
17
|
-
} from '@tanstack/react-query';
|
|
18
|
-
|
|
19
|
-
import { AxiosError } from 'axios';
|
|
20
|
-
import { api } from '${apiDirectory}';
|
|
21
|
-
import { queryClient } from '${queryClientDir}';
|
|
22
|
-
|
|
23
|
-
import {${importTypes}} from './${schemaName}'
|
|
24
|
-
|
|
25
|
-
type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput);
|
|
26
|
-
`;
|
|
27
|
-
};
|
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
import { pascal } from 'case';
|
|
2
|
-
import isEmpty from 'lodash/isEmpty';
|
|
3
|
-
import { getDocs, getResReqTypes } from './getResReqTypes';
|
|
4
|
-
/**
|
|
5
|
-
* Extract all types from #/components/requestBodies
|
|
6
|
-
*/
|
|
7
|
-
export const generateRequestBodiesDefinition = (requestBodies = {}) => {
|
|
8
|
-
if (isEmpty(requestBodies)) {
|
|
9
|
-
return '';
|
|
10
|
-
}
|
|
11
|
-
return ('\n // REQUEST BODIES \n' +
|
|
12
|
-
Object.entries(requestBodies)
|
|
13
|
-
.map(([name, requestBody]) => {
|
|
14
|
-
const doc = getDocs(requestBody);
|
|
15
|
-
const type = getResReqTypes([['', requestBody]]);
|
|
16
|
-
const isEmptyInterface = type === '{}';
|
|
17
|
-
if (isEmptyInterface) {
|
|
18
|
-
return `export type ${pascal(name)}RequestBody = ${type}`;
|
|
19
|
-
}
|
|
20
|
-
else if (type.includes('{') && !type.includes('|') && !type.includes('&')) {
|
|
21
|
-
return `${doc}export type ${pascal(name)}RequestBody = ${type}`;
|
|
22
|
-
}
|
|
23
|
-
else {
|
|
24
|
-
return `${doc}export type ${pascal(name)}RequestBody = ${type};`;
|
|
25
|
-
}
|
|
26
|
-
})
|
|
27
|
-
.join('\n\n') +
|
|
28
|
-
'\n');
|
|
29
|
-
};
|
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
import { pascal } from 'case';
|
|
2
|
-
import isEmpty from 'lodash/isEmpty';
|
|
3
|
-
import { getDocs, getResReqTypes } from './getResReqTypes';
|
|
4
|
-
/**
|
|
5
|
-
* Extract all types from #/components/responses
|
|
6
|
-
*/
|
|
7
|
-
const generateResponsesDefinition = (responses = {}) => {
|
|
8
|
-
if (isEmpty(responses)) {
|
|
9
|
-
return '';
|
|
10
|
-
}
|
|
11
|
-
return ('\n // RESPONSES \n' +
|
|
12
|
-
Object.entries(responses)
|
|
13
|
-
.map(([name, response]) => {
|
|
14
|
-
const doc = getDocs(response);
|
|
15
|
-
const type = getResReqTypes([['', response]]);
|
|
16
|
-
const isEmptyInterface = type === '{}';
|
|
17
|
-
if (isEmptyInterface) {
|
|
18
|
-
return `export type RQ${pascal(name)}Response = ${type}`;
|
|
19
|
-
}
|
|
20
|
-
else if (type.includes('{') && !type.includes('|') && !type.includes('&')) {
|
|
21
|
-
return `${doc}export type RQ${pascal(name)}Response = ${type}`;
|
|
22
|
-
}
|
|
23
|
-
else {
|
|
24
|
-
return `${doc}export type RQ${pascal(name)}Response = ${type};`;
|
|
25
|
-
}
|
|
26
|
-
})
|
|
27
|
-
.join('\n\n') +
|
|
28
|
-
'\n');
|
|
29
|
-
};
|