react-query-lightbase-codegen 0.2.0 → 0.5.0
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/lib/cjs/convertSwaggerFile.js +32 -0
- package/lib/cjs/generateHooks.js +401 -0
- package/lib/cjs/generateImports.js +31 -0
- package/lib/cjs/generateRequestBodiesDefinition.js +36 -0
- package/lib/cjs/generateResponsesDefinition.js +36 -0
- package/lib/cjs/generateSchemas.js +103 -0
- package/lib/cjs/generateSchemasDefinition.js +40 -0
- package/lib/cjs/getResReqTypes.js +162 -0
- package/lib/cjs/import-open-api.js +10 -966
- package/lib/cjs/importSpecs.js +87 -0
- package/lib/cjs/index.js +5 -3
- package/lib/cjs/react-query-codegen-import.js +20 -12
- package/lib/cjs/resolveDiscriminator.js +31 -0
- package/lib/cjs/utils.js +168 -0
- package/lib/esm/convertSwaggerFile.js +25 -0
- package/lib/esm/generateHooks.js +394 -0
- package/lib/esm/generateImports.js +27 -0
- package/lib/esm/generateRequestBodiesDefinition.js +29 -0
- package/lib/esm/generateResponsesDefinition.js +29 -0
- package/lib/esm/generateSchemas.js +96 -0
- package/lib/esm/generateSchemasDefinition.js +33 -0
- package/lib/esm/getResReqTypes.js +150 -0
- package/lib/esm/import-open-api.js +8 -949
- package/lib/esm/importSpecs.js +80 -0
- package/lib/esm/index.js +3 -2
- package/lib/esm/react-query-codegen-import.js +21 -13
- package/lib/esm/resolveDiscriminator.js +24 -0
- package/lib/esm/utils.js +156 -0
- package/package.json +17 -15
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import chalk from 'chalk';
|
|
2
|
+
import { readFileSync, writeFileSync, readdir, mkdirSync } from 'fs';
|
|
3
|
+
import { join, parse } from 'path';
|
|
4
|
+
import { convertSwaggerFile } from './convertSwaggerFile.js';
|
|
5
|
+
import { createHook } from './generateHooks.js';
|
|
6
|
+
import { generateImports } from './generateImports.js';
|
|
7
|
+
import { generateSchemas } from './generateSchemas.js';
|
|
8
|
+
export function importSpecs({ sourceDirectory, exportDirectory, apiDirectory, queryClientDir, headerFilters, overrides, }) {
|
|
9
|
+
readdir(sourceDirectory, function (err, filenames) {
|
|
10
|
+
if (err) {
|
|
11
|
+
console.log(err);
|
|
12
|
+
throw err;
|
|
13
|
+
}
|
|
14
|
+
filenames.map(async (filename) => {
|
|
15
|
+
try {
|
|
16
|
+
const data = readFileSync(join(process.cwd(), sourceDirectory + '/' + filename), 'utf-8');
|
|
17
|
+
const { ext } = parse(sourceDirectory + '/' + filename);
|
|
18
|
+
const format = ['.yaml', '.yml'].includes(ext.toLowerCase()) ? 'yaml' : 'json';
|
|
19
|
+
let spec = await convertSwaggerFile(data, format);
|
|
20
|
+
const schemaName = `useQueries${filename.split('.')[0]}.schema`;
|
|
21
|
+
const hooksName = `useQueries${filename.split('.')[0]}`;
|
|
22
|
+
const name = filename.split('.')[0];
|
|
23
|
+
mkdirSync(join(process.cwd(), `${exportDirectory}/${name}`), { recursive: true });
|
|
24
|
+
const operationIds = [];
|
|
25
|
+
let hooks = '';
|
|
26
|
+
let schemaImportsArray = [];
|
|
27
|
+
let collectedQueryImports = [];
|
|
28
|
+
Object.entries(spec.paths).forEach(([route, verbs]) => {
|
|
29
|
+
Object.entries(verbs).forEach(([verb, operation]) => {
|
|
30
|
+
if (['get', 'post', 'patch', 'put', 'delete'].includes(verb) && !operation.deprecated) {
|
|
31
|
+
const { implementation, imports, queryImports } = createHook({
|
|
32
|
+
operation,
|
|
33
|
+
verb,
|
|
34
|
+
route: (spec.basePath || '') + route,
|
|
35
|
+
operationIds,
|
|
36
|
+
parameters: verbs.parameters,
|
|
37
|
+
schemasComponents: spec.components,
|
|
38
|
+
headerFilters,
|
|
39
|
+
overrides,
|
|
40
|
+
});
|
|
41
|
+
hooks += implementation;
|
|
42
|
+
imports.forEach((element) => {
|
|
43
|
+
const formattedImport = element.replace('[]', '');
|
|
44
|
+
if (!schemaImportsArray.includes(formattedImport) &&
|
|
45
|
+
element !== 'void' &&
|
|
46
|
+
element !== 'string' &&
|
|
47
|
+
!element.includes('{')) {
|
|
48
|
+
schemaImportsArray.push(formattedImport);
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
queryImports.forEach((element) => {
|
|
52
|
+
if (!schemaImportsArray.includes(element)) {
|
|
53
|
+
collectedQueryImports.push(element);
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
});
|
|
59
|
+
const imports = generateImports({
|
|
60
|
+
apiDirectory,
|
|
61
|
+
queryClientDir,
|
|
62
|
+
schemaName,
|
|
63
|
+
schemaImports: schemaImportsArray,
|
|
64
|
+
queryImports: collectedQueryImports,
|
|
65
|
+
});
|
|
66
|
+
writeFileSync(join(process.cwd(), `${exportDirectory}/${name}/${hooksName}.tsx`), imports + hooks);
|
|
67
|
+
const schemas = generateSchemas({ spec });
|
|
68
|
+
writeFileSync(join(process.cwd(), `${exportDirectory}/${name}/${schemaName}.tsx`), schemas);
|
|
69
|
+
console.log(chalk.green(`🎉 [${filename}] Your OpenAPI spec has been converted into react query hooks`));
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
if (error.code === 'EISDIR') {
|
|
73
|
+
console.log(chalk.red('nested folder structure not supported'));
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
console.log(chalk.red(`[${filename}]:`), chalk.red(error));
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
}
|
package/lib/esm/index.js
CHANGED
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { convertSwaggerFile } from './convertSwaggerFile.js';
|
|
2
|
+
import { importSpecs } from './importSpecs.js';
|
|
3
|
+
export { importSpecs, convertSwaggerFile };
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import chalk from 'chalk';
|
|
2
|
-
import { readFileSync, writeFileSync, readdir } from 'fs';
|
|
2
|
+
import { readFileSync, writeFileSync, readdir, mkdirSync } from 'fs';
|
|
3
3
|
import { join, parse } from 'path';
|
|
4
|
-
import {
|
|
5
|
-
|
|
6
|
-
|
|
4
|
+
import { convertSwaggerFile } from './convertSwaggerFile';
|
|
5
|
+
import { generateQueryHooks } from './generateHooks';
|
|
6
|
+
import { generateSchemas } from './generateSchemas';
|
|
7
7
|
export function importSpecs({ sourceDirectory, exportDirectory, apiDirectory, queryClientDir, headerFilters, }) {
|
|
8
8
|
readdir(sourceDirectory, function (err, filenames) {
|
|
9
9
|
if (err) {
|
|
10
|
+
console.log(err);
|
|
10
11
|
throw err;
|
|
11
12
|
}
|
|
12
13
|
filenames.map(async (filename) => {
|
|
@@ -14,20 +15,27 @@ export function importSpecs({ sourceDirectory, exportDirectory, apiDirectory, qu
|
|
|
14
15
|
const { ext } = parse(sourceDirectory + '/' + filename);
|
|
15
16
|
const format = ['.yaml', '.yml'].includes(ext.toLowerCase()) ? 'yaml' : 'json';
|
|
16
17
|
try {
|
|
17
|
-
const name =
|
|
18
|
-
const
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
18
|
+
const name = filename.split('.')[0];
|
|
19
|
+
const hooksName = `useQueries${filename.split('.')[0]}`;
|
|
20
|
+
const schemaName = `useQueries${filename.split('.')[0]}.schema`;
|
|
21
|
+
let spec = await convertSwaggerFile(data, format);
|
|
22
|
+
const operationIds = [];
|
|
23
|
+
mkdirSync(join(process.cwd(), `${exportDirectory}/${name}`), { recursive: true });
|
|
24
|
+
const hooks = generateQueryHooks({
|
|
25
|
+
spec,
|
|
26
|
+
schemaName,
|
|
27
|
+
operationIds,
|
|
22
28
|
headerFilters,
|
|
29
|
+
apiDirectory,
|
|
23
30
|
queryClientDir,
|
|
24
31
|
});
|
|
25
|
-
writeFileSync(join(process.cwd(), `${exportDirectory}/${name}`),
|
|
26
|
-
|
|
32
|
+
writeFileSync(join(process.cwd(), `${exportDirectory}/${name}/${hooksName}.tsx`), hooks);
|
|
33
|
+
const schemas = generateSchemas(spec);
|
|
34
|
+
writeFileSync(join(process.cwd(), `${exportDirectory}/${name}/${schemaName}.tsx`), schemas);
|
|
35
|
+
console.log(chalk.green(`🎉 [${filename}] Your OpenAPI spec has been converted into react query hooks`));
|
|
27
36
|
}
|
|
28
37
|
catch (error) {
|
|
29
|
-
log(chalk.red(`[${filename}]:`), chalk.red(error));
|
|
30
|
-
// process.exit(1);
|
|
38
|
+
console.log(chalk.red(`[${filename}]:`), chalk.red(error));
|
|
31
39
|
}
|
|
32
40
|
});
|
|
33
41
|
});
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import set from 'lodash/set';
|
|
2
|
+
import { isReference } from './getResReqTypes';
|
|
3
|
+
/**
|
|
4
|
+
* Propagate every `discriminator.propertyName` mapping to the original ref
|
|
5
|
+
*
|
|
6
|
+
* Note: This method directly mutate the `specs` object.
|
|
7
|
+
*/
|
|
8
|
+
export const resolveDiscriminator = (specs) => {
|
|
9
|
+
if (specs.components && specs.components.schemas) {
|
|
10
|
+
Object.values(specs.components.schemas).forEach((schema) => {
|
|
11
|
+
if (isReference(schema) || !schema.discriminator || !schema.discriminator.mapping) {
|
|
12
|
+
return;
|
|
13
|
+
}
|
|
14
|
+
const { mapping, propertyName } = schema.discriminator;
|
|
15
|
+
Object.entries(mapping).forEach(([name, ref]) => {
|
|
16
|
+
if (!ref.startsWith('#/components/schemas/')) {
|
|
17
|
+
throw new Error('Discriminator mapping outside of `#/components/schemas` is not supported');
|
|
18
|
+
}
|
|
19
|
+
console.log('HELLO');
|
|
20
|
+
set(specs, `components.schemas.${ref.slice('#/components/schemas/'.length)}.properties.${propertyName}.enum`, [name]);
|
|
21
|
+
});
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
};
|
package/lib/esm/utils.js
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import lodash from 'lodash';
|
|
2
|
+
const { uniq, isEmpty } = lodash;
|
|
3
|
+
import pasCase from 'case';
|
|
4
|
+
const { pascal } = pasCase;
|
|
5
|
+
export const getDocs = (data) => isReference(data) ? '' : formatDescription(data.description);
|
|
6
|
+
/**
|
|
7
|
+
* Discriminator helper for `ReferenceObject`
|
|
8
|
+
*/
|
|
9
|
+
export const isReference = (property) => {
|
|
10
|
+
return Boolean(property.$ref);
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Return the typescript equivalent of open-api data type
|
|
14
|
+
*/
|
|
15
|
+
export const getScalar = (item) => {
|
|
16
|
+
const nullable = item.nullable ? ' | null' : '';
|
|
17
|
+
switch (item.type) {
|
|
18
|
+
case 'number':
|
|
19
|
+
case 'integer':
|
|
20
|
+
return 'number' + nullable;
|
|
21
|
+
case 'boolean':
|
|
22
|
+
return 'boolean' + nullable;
|
|
23
|
+
case 'array':
|
|
24
|
+
return getArray(item) + nullable;
|
|
25
|
+
case 'string':
|
|
26
|
+
return (item.enum ? `"${item.enum.join(`" | "`)}"` : 'string') + nullable;
|
|
27
|
+
case 'object':
|
|
28
|
+
default:
|
|
29
|
+
return getObject(item) + nullable;
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Return the output type from the $ref
|
|
34
|
+
*/
|
|
35
|
+
const getRef = ($ref) => {
|
|
36
|
+
if ($ref.startsWith('#/components/schemas')) {
|
|
37
|
+
return pascal($ref.replace('#/components/schemas/', ''));
|
|
38
|
+
}
|
|
39
|
+
else if ($ref.startsWith('#/components/responses')) {
|
|
40
|
+
return pascal($ref.replace('#/components/responses/', '')) + 'Response';
|
|
41
|
+
}
|
|
42
|
+
else if ($ref.startsWith('#/components/parameters')) {
|
|
43
|
+
return pascal($ref.replace('#/components/parameters/', '')) + 'Parameter';
|
|
44
|
+
}
|
|
45
|
+
else if ($ref.startsWith('#/components/requestBodies')) {
|
|
46
|
+
return pascal($ref.replace('#/components/requestBodies/', '')) + 'RequestBody';
|
|
47
|
+
}
|
|
48
|
+
else {
|
|
49
|
+
throw new Error('This library only resolve $ref that are include into `#/components/*` for now');
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* Return the output type from an array
|
|
54
|
+
*/
|
|
55
|
+
const getArray = (item) => {
|
|
56
|
+
if (item.items) {
|
|
57
|
+
if (!isReference(item.items) && (item.items.oneOf || item.items.allOf || item.items.enum)) {
|
|
58
|
+
return `(${resolveValue(item.items)})[]`;
|
|
59
|
+
}
|
|
60
|
+
else {
|
|
61
|
+
return `${resolveValue(item.items)}[]`;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
else {
|
|
65
|
+
throw new Error('All arrays must have an `items` key define');
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
/**
|
|
69
|
+
* Return the output type from an object
|
|
70
|
+
*/
|
|
71
|
+
const getObject = (item) => {
|
|
72
|
+
if (isReference(item)) {
|
|
73
|
+
return getRef(item.$ref);
|
|
74
|
+
}
|
|
75
|
+
if (item.allOf) {
|
|
76
|
+
return item.allOf.map(resolveValue).join(' & ');
|
|
77
|
+
}
|
|
78
|
+
if (item.oneOf) {
|
|
79
|
+
return item.oneOf.map(resolveValue).join(' | ');
|
|
80
|
+
}
|
|
81
|
+
if (!item.type && !item.properties && !item.additionalProperties) {
|
|
82
|
+
return '{}';
|
|
83
|
+
}
|
|
84
|
+
// Free form object (https://swagger.io/docs/specification/data-models/data-types/#free-form)
|
|
85
|
+
if (item.type === 'object' &&
|
|
86
|
+
!item.properties &&
|
|
87
|
+
(!item.additionalProperties || item.additionalProperties === true || isEmpty(item.additionalProperties))) {
|
|
88
|
+
return '{[key: string]: any}';
|
|
89
|
+
}
|
|
90
|
+
const IdentifierRegexp = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
|
|
91
|
+
// Consolidation of item.properties & item.additionalProperties
|
|
92
|
+
let output = '{\n';
|
|
93
|
+
if (item.properties) {
|
|
94
|
+
output += Object.entries(item.properties)
|
|
95
|
+
.map(([key, prop]) => {
|
|
96
|
+
const doc = getDocs(prop);
|
|
97
|
+
const isRequired = (item.required || []).includes(key);
|
|
98
|
+
const processedKey = IdentifierRegexp.test(key) ? key : `"${key}"`;
|
|
99
|
+
return `${doc}\n${processedKey}${isRequired ? '' : '?'}: ${resolveValue(prop)};`;
|
|
100
|
+
})
|
|
101
|
+
.join('');
|
|
102
|
+
}
|
|
103
|
+
if (item.additionalProperties) {
|
|
104
|
+
if (item.properties) {
|
|
105
|
+
output += '\n';
|
|
106
|
+
}
|
|
107
|
+
output += `} & { [key: string]: ${item.additionalProperties === true ? 'any' : resolveValue(item.additionalProperties)}`;
|
|
108
|
+
}
|
|
109
|
+
if (item.properties || item.additionalProperties) {
|
|
110
|
+
if (output === '{\n') {
|
|
111
|
+
return '{}';
|
|
112
|
+
}
|
|
113
|
+
return output + '\n}';
|
|
114
|
+
}
|
|
115
|
+
return item.type === 'object' ? '{[key: string]: any}' : 'any';
|
|
116
|
+
};
|
|
117
|
+
/**
|
|
118
|
+
* Resolve the value of a schema object to a proper type definition.
|
|
119
|
+
*/
|
|
120
|
+
export const resolveValue = (schema) => isReference(schema) ? getRef(schema.$ref) : getScalar(schema);
|
|
121
|
+
/**
|
|
122
|
+
* Format a description to code documentation.
|
|
123
|
+
*/
|
|
124
|
+
export const formatDescription = (description) => {
|
|
125
|
+
if (!description) {
|
|
126
|
+
return '';
|
|
127
|
+
}
|
|
128
|
+
return `\n/**\n${description
|
|
129
|
+
.split('\n')
|
|
130
|
+
.map((i) => `* ${i}`)
|
|
131
|
+
.join('\n')}\n */`;
|
|
132
|
+
};
|
|
133
|
+
/**
|
|
134
|
+
* Extract responses / request types from open-api specs
|
|
135
|
+
*/
|
|
136
|
+
export const getResReqTypes = (responsesOrRequests) => {
|
|
137
|
+
return uniq(responsesOrRequests.map(([_, res]) => {
|
|
138
|
+
if (!res) {
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
if (isReference(res)) {
|
|
142
|
+
return getRef(res.$ref);
|
|
143
|
+
}
|
|
144
|
+
if (res.content) {
|
|
145
|
+
for (let contentType of Object.keys(res.content)) {
|
|
146
|
+
if (contentType.startsWith('application/json') ||
|
|
147
|
+
contentType.startsWith('application/octet-stream')) {
|
|
148
|
+
const schema = res.content[contentType].schema;
|
|
149
|
+
return resolveValue(schema);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
return;
|
|
155
|
+
})).join(' | ');
|
|
156
|
+
};
|
package/package.json
CHANGED
|
@@ -1,43 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "react-query-lightbase-codegen",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"license": "MIT",
|
|
5
|
-
"
|
|
6
|
-
"
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": "./src/index.js",
|
|
7
7
|
"files": [
|
|
8
8
|
"lib/"
|
|
9
9
|
],
|
|
10
|
+
"engines": {
|
|
11
|
+
"node": ">=14.16"
|
|
12
|
+
},
|
|
10
13
|
"scripts": {
|
|
11
14
|
"lint": "eslint . --ext .js,.jsx,.ts,.tsx",
|
|
12
15
|
"tsc": "tsc -p tsconfig.json && tsc -p tsconfig-cjs.json",
|
|
13
|
-
"test": "yarn tsc && node test/script.mjs &&
|
|
16
|
+
"test": "yarn tsc && node test/script.mjs && prettier --check ./test/generated/**/*.tsx --write && eslint ./test/generated/**/*.tsx --fix"
|
|
14
17
|
},
|
|
15
18
|
"dependencies": {
|
|
16
|
-
"@tanstack/react-query": "^4.0.9",
|
|
17
19
|
"axios": "0.27.2",
|
|
18
20
|
"case": "1.6.3",
|
|
19
|
-
"chalk": "
|
|
21
|
+
"chalk": "5.0.1",
|
|
20
22
|
"js-yaml": "4.1.0",
|
|
21
23
|
"lodash": "4.17.21",
|
|
22
24
|
"openapi3-ts": "2.0.2",
|
|
23
|
-
"qs": "6.10.3",
|
|
24
|
-
"query-string": "7.1.1",
|
|
25
25
|
"swagger2openapi": "7.0.8",
|
|
26
26
|
"yamljs": "0.3.0"
|
|
27
27
|
},
|
|
28
28
|
"devDependencies": {
|
|
29
|
-
"@babel/core": "7.
|
|
29
|
+
"@babel/core": "7.18.10",
|
|
30
30
|
"@babel/eslint-parser": "7.17.0",
|
|
31
|
-
"@react-native-community/eslint-config": "3.0
|
|
31
|
+
"@react-native-community/eslint-config": "3.1.0",
|
|
32
|
+
"@tanstack/react-query": "4.0.10",
|
|
33
|
+
"@types/js-yaml": "4.0.5",
|
|
32
34
|
"@types/lodash": "4.14.182",
|
|
33
|
-
"@types/node": "
|
|
35
|
+
"@types/node": "18.6.3",
|
|
34
36
|
"@types/qs": "6.9.7",
|
|
35
37
|
"@types/query-string": "6.3.0",
|
|
36
38
|
"@types/yamljs": "0.2.31",
|
|
37
|
-
"eslint": "8.
|
|
38
|
-
"eslint-plugin-prettier": "4.
|
|
39
|
-
"prettier": "2.
|
|
39
|
+
"eslint": "8.21.0",
|
|
40
|
+
"eslint-plugin-prettier": "4.2.1",
|
|
41
|
+
"prettier": "2.7.1",
|
|
40
42
|
"react": "17.0.2",
|
|
41
|
-
"typescript": "4.
|
|
43
|
+
"typescript": "4.7.4"
|
|
42
44
|
}
|
|
43
45
|
}
|