react-query-lightbase-codegen 1.1.1 → 1.1.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/dist/convertSwaggerFile.d.ts +5 -0
- package/{lib/esm → dist}/convertSwaggerFile.js +1 -0
- package/dist/convertSwaggerFile.js.map +1 -0
- package/dist/generateHooks.d.ts +25 -0
- package/dist/generateHooks.js +393 -0
- package/dist/generateHooks.js.map +1 -0
- package/dist/generateImports.d.ts +7 -0
- package/dist/generateImports.js +28 -0
- package/dist/generateImports.js.map +1 -0
- package/dist/generateSchemas.d.ts +7 -0
- package/{lib/esm → dist}/generateSchemas.js +7 -7
- package/dist/generateSchemas.js.map +1 -0
- package/dist/importSpecs.d.ts +15 -0
- package/dist/importSpecs.js +90 -0
- package/dist/importSpecs.js.map +1 -0
- package/{lib/esm/index.js → dist/index.d.ts} +0 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -0
- package/dist/utils.d.ts +24 -0
- package/{lib/esm → dist}/utils.js +22 -18
- package/dist/utils.js.map +1 -0
- package/package.json +3 -3
- package/lib/cjs/convertSwaggerFile.js +0 -32
- package/lib/cjs/generateHooks.js +0 -368
- package/lib/cjs/generateImports.js +0 -26
- package/lib/cjs/generateSchemas.js +0 -104
- package/lib/cjs/importSpecs.js +0 -46
- package/lib/cjs/index.js +0 -7
- package/lib/cjs/utils.js +0 -165
- package/lib/esm/generateHooks.js +0 -360
- package/lib/esm/generateImports.js +0 -22
- package/lib/esm/importSpecs.js +0 -39
|
@@ -1,104 +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.generateSchemas = void 0;
|
|
7
|
-
const case_1 = __importDefault(require("case"));
|
|
8
|
-
const lodash_1 = __importDefault(require("lodash"));
|
|
9
|
-
const { isEmpty } = lodash_1.default;
|
|
10
|
-
const { pascal } = case_1.default;
|
|
11
|
-
const utils_js_1 = require("./utils.js");
|
|
12
|
-
const utils_js_2 = require("./utils.js");
|
|
13
|
-
/**
|
|
14
|
-
* Generate the interface string
|
|
15
|
-
*/
|
|
16
|
-
const generateInterface = (name, schema) => {
|
|
17
|
-
const scalar = (0, utils_js_1.getScalar)(schema);
|
|
18
|
-
return `
|
|
19
|
-
${(0, utils_js_1.formatDescription)(schema.description)}
|
|
20
|
-
export type ${pascal(name)} = ${scalar}
|
|
21
|
-
`;
|
|
22
|
-
};
|
|
23
|
-
/**
|
|
24
|
-
* Extract all types from #/components/schemas
|
|
25
|
-
*/
|
|
26
|
-
const generateSchemasDefinition = (schemas = {}) => {
|
|
27
|
-
if (isEmpty(schemas)) {
|
|
28
|
-
return '';
|
|
29
|
-
}
|
|
30
|
-
return ('\n // SCEHMAS \n' +
|
|
31
|
-
Object.entries(schemas)
|
|
32
|
-
.map(([name, schema]) => !(0, utils_js_1.isReference)(schema) &&
|
|
33
|
-
(!schema.type || schema.type === 'object') &&
|
|
34
|
-
!schema.allOf &&
|
|
35
|
-
!schema.oneOf &&
|
|
36
|
-
!(0, utils_js_1.isReference)(schema) &&
|
|
37
|
-
!schema.nullable
|
|
38
|
-
? generateInterface(name, schema)
|
|
39
|
-
: `${(0, utils_js_1.formatDescription)((0, utils_js_1.isReference)(schema) ? undefined : schema.description)} export type ${pascal(name)} = ${(0, utils_js_1.resolveValue)(schema)};`)
|
|
40
|
-
.join('\n\n') +
|
|
41
|
-
'\n');
|
|
42
|
-
};
|
|
43
|
-
/**
|
|
44
|
-
* Extract all types from #/components/requestBodies
|
|
45
|
-
*/
|
|
46
|
-
const generateRequestBodiesDefinition = (requestBodies = {}) => {
|
|
47
|
-
if (isEmpty(requestBodies)) {
|
|
48
|
-
return '';
|
|
49
|
-
}
|
|
50
|
-
return ('\n // REQUEST BODIES \n' +
|
|
51
|
-
Object.entries(requestBodies)
|
|
52
|
-
.map(([name, requestBody]) => {
|
|
53
|
-
const doc = (0, utils_js_2.getDocs)(requestBody);
|
|
54
|
-
const type = (0, utils_js_2.getResReqTypes)([['', requestBody]]);
|
|
55
|
-
const isEmptyInterface = type === '{}';
|
|
56
|
-
if (isEmptyInterface) {
|
|
57
|
-
return `${doc}export type ${pascal(name)}RequestBody = ${type}`;
|
|
58
|
-
}
|
|
59
|
-
else if (type.includes('{') && !type.includes('|') && !type.includes('&')) {
|
|
60
|
-
return `${doc}export type ${pascal(name)}RequestBody = ${type}`;
|
|
61
|
-
}
|
|
62
|
-
else {
|
|
63
|
-
return `${doc}export type ${pascal(name)}RequestBody = ${type};`;
|
|
64
|
-
}
|
|
65
|
-
})
|
|
66
|
-
.join('\n\n') +
|
|
67
|
-
'\n');
|
|
68
|
-
};
|
|
69
|
-
/**
|
|
70
|
-
* Extract all types from #/components/responses
|
|
71
|
-
*/
|
|
72
|
-
const generateResponsesDefinition = (responses = {}) => {
|
|
73
|
-
if (isEmpty(responses)) {
|
|
74
|
-
return '';
|
|
75
|
-
}
|
|
76
|
-
return ('\n // RESPONSES \n' +
|
|
77
|
-
Object.entries(responses)
|
|
78
|
-
.map(([name, response]) => {
|
|
79
|
-
const doc = (0, utils_js_2.getDocs)(response);
|
|
80
|
-
const type = (0, utils_js_2.getResReqTypes)([['', response]]);
|
|
81
|
-
const isEmptyInterface = type === '{}';
|
|
82
|
-
if (isEmptyInterface) {
|
|
83
|
-
return `export type RQ${pascal(name)}Response = ${type}`;
|
|
84
|
-
}
|
|
85
|
-
else if (type.includes('{') && !type.includes('|') && !type.includes('&')) {
|
|
86
|
-
return `${doc}export type RQ${pascal(name)}Response = ${type}`;
|
|
87
|
-
}
|
|
88
|
-
else {
|
|
89
|
-
return `${doc}export type RQ${pascal(name)}Response = ${type};`;
|
|
90
|
-
}
|
|
91
|
-
})
|
|
92
|
-
.join('\n\n') +
|
|
93
|
-
'\n');
|
|
94
|
-
};
|
|
95
|
-
/**
|
|
96
|
-
* Extract all types from #/components/schemas
|
|
97
|
-
*/
|
|
98
|
-
const generateSchemas = ({ spec }) => {
|
|
99
|
-
const schemaOutput = generateSchemasDefinition(spec.components?.schemas) +
|
|
100
|
-
generateResponsesDefinition(spec.components?.responses) +
|
|
101
|
-
generateRequestBodiesDefinition(spec.components?.requestBodies);
|
|
102
|
-
return schemaOutput;
|
|
103
|
-
};
|
|
104
|
-
exports.generateSchemas = generateSchemas;
|
package/lib/cjs/importSpecs.js
DELETED
|
@@ -1,46 +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.importSpecs = void 0;
|
|
7
|
-
const chalk_1 = __importDefault(require("chalk"));
|
|
8
|
-
const fs_1 = require("fs");
|
|
9
|
-
const path_1 = require("path");
|
|
10
|
-
const convertSwaggerFile_js_1 = require("./convertSwaggerFile.js");
|
|
11
|
-
const generateHooks_js_1 = require("./generateHooks.js");
|
|
12
|
-
const generateSchemas_js_1 = require("./generateSchemas.js");
|
|
13
|
-
function importSpecs({ sourceDirectory, exportDirectory, apiDirectory, queryClientDir, headerFilters, }) {
|
|
14
|
-
(0, fs_1.readdir)(sourceDirectory, function (err, filenames) {
|
|
15
|
-
if (err) {
|
|
16
|
-
console.log(err);
|
|
17
|
-
throw err;
|
|
18
|
-
}
|
|
19
|
-
filenames.map(async (filename) => {
|
|
20
|
-
try {
|
|
21
|
-
const data = (0, fs_1.readFileSync)((0, path_1.join)(process.cwd(), sourceDirectory + '/' + filename), 'utf-8');
|
|
22
|
-
const { ext } = (0, path_1.parse)(sourceDirectory + '/' + filename);
|
|
23
|
-
const format = ['.yaml', '.yml'].includes(ext.toLowerCase()) ? 'yaml' : 'json';
|
|
24
|
-
const name = filename.split('.')[0];
|
|
25
|
-
let spec = await (0, convertSwaggerFile_js_1.convertSwaggerFile)(data, format);
|
|
26
|
-
const operationIds = [];
|
|
27
|
-
(0, fs_1.mkdirSync)((0, path_1.join)(process.cwd(), `${exportDirectory}/${name}`), { recursive: true });
|
|
28
|
-
const { implementation, schemaImports } = (0, generateHooks_js_1.generateQueryHooks)({ spec, operationIds, headerFilters });
|
|
29
|
-
const schemaName = `useQueries${filename.split('.')[0]}.schema`;
|
|
30
|
-
const imports = (0, generateHooks_js_1.generateImports)({ apiDirectory, queryClientDir, schemaName, schemaImports });
|
|
31
|
-
const hooksName = `useQueries${filename.split('.')[0]}`;
|
|
32
|
-
(0, fs_1.writeFileSync)((0, path_1.join)(process.cwd(), `${exportDirectory}/${name}/${hooksName}.tsx`), imports + implementation);
|
|
33
|
-
const schemas = (0, generateSchemas_js_1.generateSchemas)({ spec });
|
|
34
|
-
(0, fs_1.writeFileSync)((0, path_1.join)(process.cwd(), `${exportDirectory}/${name}/${schemaName}.tsx`), schemas);
|
|
35
|
-
console.log(chalk_1.default.green(`🎉 [${filename}] Your OpenAPI spec has been converted into react query hooks`));
|
|
36
|
-
}
|
|
37
|
-
catch (error) {
|
|
38
|
-
if (error.code === 'EISDIR') {
|
|
39
|
-
return;
|
|
40
|
-
}
|
|
41
|
-
console.log(chalk_1.default.red(`[${filename}]:`), chalk_1.default.red(error));
|
|
42
|
-
}
|
|
43
|
-
});
|
|
44
|
-
});
|
|
45
|
-
}
|
|
46
|
-
exports.importSpecs = importSpecs;
|
package/lib/cjs/index.js
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.convertSwaggerFile = exports.importSpecs = void 0;
|
|
4
|
-
const convertSwaggerFile_js_1 = require("./convertSwaggerFile.js");
|
|
5
|
-
Object.defineProperty(exports, "convertSwaggerFile", { enumerable: true, get: function () { return convertSwaggerFile_js_1.convertSwaggerFile; } });
|
|
6
|
-
const importSpecs_js_1 = require("./importSpecs.js");
|
|
7
|
-
Object.defineProperty(exports, "importSpecs", { enumerable: true, get: function () { return importSpecs_js_1.importSpecs; } });
|
package/lib/cjs/utils.js
DELETED
|
@@ -1,165 +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
|
-
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;
|
package/lib/esm/generateHooks.js
DELETED
|
@@ -1,360 +0,0 @@
|
|
|
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
|
-
};
|