react-query-lightbase-codegen 1.0.0 → 1.0.3

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.
@@ -1,96 +0,0 @@
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 `${formatDescription(schema.description)}
13
- export type ${pascal(name)} = ${scalar}
14
- `;
15
- };
16
- /**
17
- * Extract all types from #/components/schemas
18
- */
19
- const generateSchemasDefinition = (schemas = {}) => {
20
- if (isEmpty(schemas)) {
21
- return '';
22
- }
23
- return ('\n // SCEHMAS \n' +
24
- Object.entries(schemas)
25
- .map(([name, schema]) => !isReference(schema) &&
26
- (!schema.type || schema.type === 'object') &&
27
- !schema.allOf &&
28
- !schema.oneOf &&
29
- !isReference(schema) &&
30
- !schema.nullable
31
- ? generateInterface(name, schema)
32
- : `${formatDescription(isReference(schema) ? undefined : schema.description)} export type ${pascal(name)} = ${resolveValue(schema)};`)
33
- .join('\n\n') +
34
- '\n');
35
- };
36
- /**
37
- * Extract all types from #/components/requestBodies
38
- */
39
- const generateRequestBodiesDefinition = (requestBodies = {}) => {
40
- if (isEmpty(requestBodies)) {
41
- return '';
42
- }
43
- return ('\n // REQUEST BODIES \n' +
44
- Object.entries(requestBodies)
45
- .map(([name, requestBody]) => {
46
- const doc = getDocs(requestBody);
47
- const type = getResReqTypes([['', requestBody]]);
48
- const isEmptyInterface = type === '{}';
49
- if (isEmptyInterface) {
50
- return `${doc}\nexport type ${pascal(name)}RequestBody = ${type}`;
51
- }
52
- else if (type.includes('{') && !type.includes('|') && !type.includes('&')) {
53
- return `${doc}\nexport type ${pascal(name)}RequestBody = ${type}`;
54
- }
55
- else {
56
- return `${doc}\nexport type ${pascal(name)}RequestBody = ${type};`;
57
- }
58
- })
59
- .join('\n\n') +
60
- '\n');
61
- };
62
- /**
63
- * Extract all types from #/components/responses
64
- */
65
- const generateResponsesDefinition = (responses = {}) => {
66
- if (isEmpty(responses)) {
67
- return '';
68
- }
69
- return ('\n // RESPONSES \n' +
70
- Object.entries(responses)
71
- .map(([name, response]) => {
72
- const doc = getDocs(response);
73
- const type = getResReqTypes([['', response]]);
74
- const isEmptyInterface = type === '{}';
75
- if (isEmptyInterface) {
76
- return `export type RQ${pascal(name)}Response = ${type}`;
77
- }
78
- else if (type.includes('{') && !type.includes('|') && !type.includes('&')) {
79
- return `${doc}export type RQ${pascal(name)}Response = ${type}`;
80
- }
81
- else {
82
- return `${doc}export type RQ${pascal(name)}Response = ${type};`;
83
- }
84
- })
85
- .join('\n\n') +
86
- '\n');
87
- };
88
- /**
89
- * Extract all types from #/components/schemas
90
- */
91
- export const generateSchemas = ({ spec }) => {
92
- const schemaOutput = generateRequestBodiesDefinition(spec.components?.requestBodies) +
93
- generateResponsesDefinition(spec.components?.responses) +
94
- generateSchemasDefinition(spec.components?.schemas);
95
- return schemaOutput;
96
- };
@@ -1,80 +0,0 @@
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/utils.js DELETED
@@ -1,156 +0,0 @@
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
- };