react-query-lightbase-codegen 1.0.2 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,110 @@
1
+ import chalk from 'chalk';
2
+ import { readFileSync, writeFileSync, readdir, mkdirSync } from 'fs';
3
+ import { OperationObject, PathItemObject } from 'openapi3-ts';
4
+ import { join, parse } from 'path';
5
+ import { convertSwaggerFile } from './convertSwaggerFile.js';
6
+ import { createHook } from './generateHooks.js';
7
+ import { generateImports } from './generateImports.js';
8
+ import { generateSchemas } from './generateSchemas.js';
9
+
10
+ export function importSpecs({
11
+ sourceDirectory,
12
+ exportDirectory,
13
+ apiDirectory,
14
+ queryClientDir,
15
+ headerFilters,
16
+ overrides,
17
+ }: {
18
+ sourceDirectory: string;
19
+ exportDirectory: string;
20
+ apiDirectory: string;
21
+ queryClientDir: string;
22
+ headerFilters?: string[];
23
+ overrides?: Record<
24
+ string,
25
+ { type: 'query' } | { type: 'mutation' } | { type: 'infiniteQuery'; infiniteQueryParm: string }
26
+ >;
27
+ }) {
28
+ readdir(sourceDirectory, function (err, filenames) {
29
+ if (err) {
30
+ console.log(err);
31
+ throw err;
32
+ }
33
+ filenames.map(async (filename) => {
34
+ try {
35
+ const data = readFileSync(join(process.cwd(), sourceDirectory + '/' + filename), 'utf-8');
36
+ const { ext } = parse(sourceDirectory + '/' + filename);
37
+ const format = ['.yaml', '.yml'].includes(ext.toLowerCase()) ? 'yaml' : 'json';
38
+ let spec = await convertSwaggerFile(data, format);
39
+
40
+ const schemaName = `useQueries${filename.split('.')[0]}.schema`;
41
+ const hooksName = `useQueries${filename.split('.')[0]}`;
42
+ const name = filename.split('.')[0];
43
+ mkdirSync(join(process.cwd(), `${exportDirectory}/${name}`), { recursive: true });
44
+
45
+ const operationIds: string[] = [];
46
+
47
+ let hooks = '';
48
+ let schemaImportsArray = [] as string[];
49
+ let collectedQueryImports = [] as ('query' | 'mutation' | 'infiniteQuery')[];
50
+ Object.entries(spec.paths).forEach(([route, verbs]: [string, PathItemObject]) => {
51
+ Object.entries(verbs).forEach(([verb, operation]: [string, OperationObject]) => {
52
+ if (['get', 'post', 'patch', 'put', 'delete'].includes(verb) && !operation.deprecated) {
53
+ const { implementation, imports, queryImports } = createHook({
54
+ operation,
55
+ verb,
56
+ route: (spec.basePath || '') + route,
57
+ operationIds,
58
+ parameters: verbs.parameters,
59
+ schemasComponents: spec.components,
60
+ headerFilters,
61
+ overrides,
62
+ });
63
+
64
+ hooks += implementation;
65
+ imports.forEach((element) => {
66
+ const formattedImport = element.replace('[]', '');
67
+ if (
68
+ !schemaImportsArray.includes(formattedImport) &&
69
+ element !== 'void' &&
70
+ element !== 'string' &&
71
+ !element.includes('{')
72
+ ) {
73
+ schemaImportsArray.push(formattedImport);
74
+ }
75
+ });
76
+ queryImports.forEach((element) => {
77
+ if (!schemaImportsArray.includes(element)) {
78
+ collectedQueryImports.push(element);
79
+ }
80
+ });
81
+ }
82
+ });
83
+ });
84
+
85
+ const imports = generateImports({
86
+ apiDirectory,
87
+ queryClientDir,
88
+ schemaName,
89
+ schemaImports: schemaImportsArray,
90
+ queryImports: collectedQueryImports,
91
+ });
92
+
93
+ writeFileSync(join(process.cwd(), `${exportDirectory}/${name}/${hooksName}.tsx`), imports + hooks);
94
+
95
+ const schemas = generateSchemas({ spec });
96
+ writeFileSync(join(process.cwd(), `${exportDirectory}/${name}/${schemaName}.tsx`), schemas);
97
+
98
+ console.log(
99
+ chalk.green(`🎉 [${filename}] Your OpenAPI spec has been converted into react query hooks`)
100
+ );
101
+ } catch (error) {
102
+ if ((error as any).code === 'EISDIR') {
103
+ console.log(chalk.red('nested folder structure not supported'));
104
+ return;
105
+ }
106
+ console.log(chalk.red(`[${filename}]:`), chalk.red(error));
107
+ }
108
+ });
109
+ });
110
+ }
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ import { convertSwaggerFile } from './convertSwaggerFile.js';
2
+ import { importSpecs } from './importSpecs.js';
3
+ export { importSpecs, convertSwaggerFile };
package/src/utils.ts ADDED
@@ -0,0 +1,190 @@
1
+ import lodash from 'lodash';
2
+ const { uniq, isEmpty } = lodash;
3
+ import pasCase from 'case';
4
+
5
+ const { pascal } = pasCase;
6
+
7
+ import { ReferenceObject, RequestBodyObject, ResponseObject, SchemaObject } from 'openapi3-ts';
8
+
9
+ export const getDocs = (data: ReferenceObject | { description?: string }) =>
10
+ isReference(data) ? '' : formatDescription(data.description);
11
+ /**
12
+ * Discriminator helper for `ReferenceObject`
13
+ */
14
+ export const isReference = (property: any): property is ReferenceObject => {
15
+ return Boolean(property.$ref);
16
+ };
17
+
18
+ /**
19
+ * Return the typescript equivalent of open-api data type
20
+ */
21
+ export const getScalar = (item: SchemaObject) => {
22
+ const nullable = item.nullable ? ' | null' : '';
23
+
24
+ switch (item.type) {
25
+ case 'number':
26
+ case 'integer':
27
+ return 'number' + nullable;
28
+
29
+ case 'boolean':
30
+ return 'boolean' + nullable;
31
+
32
+ case 'array':
33
+ return getArray(item) + nullable;
34
+
35
+ case 'string':
36
+ return (item.enum ? `"${item.enum.join(`" | "`)}"` : 'string') + nullable;
37
+
38
+ case 'object':
39
+ default:
40
+ return getObject(item) + nullable;
41
+ }
42
+ };
43
+
44
+ /**
45
+ * Return the output type from the $ref
46
+ */
47
+ const getRef = ($ref: ReferenceObject['$ref']) => {
48
+ if ($ref.startsWith('#/components/schemas')) {
49
+ return pascal($ref.replace('#/components/schemas/', ''));
50
+ } else if ($ref.startsWith('#/components/responses')) {
51
+ return pascal($ref.replace('#/components/responses/', '')) + 'Response';
52
+ } else if ($ref.startsWith('#/components/parameters')) {
53
+ return pascal($ref.replace('#/components/parameters/', '')) + 'Parameter';
54
+ } else if ($ref.startsWith('#/components/requestBodies')) {
55
+ return pascal($ref.replace('#/components/requestBodies/', '')) + 'RequestBody';
56
+ } else {
57
+ throw new Error('This library only resolve $ref that are include into `#/components/*` for now');
58
+ }
59
+ };
60
+
61
+ /**
62
+ * Return the output type from an array
63
+ */
64
+ const getArray = (item: SchemaObject): string => {
65
+ if (item.items) {
66
+ if (!isReference(item.items) && (item.items.oneOf || item.items.allOf || item.items.enum)) {
67
+ return `(${resolveValue(item.items)})[]`;
68
+ } else {
69
+ return `${resolveValue(item.items)}[]`;
70
+ }
71
+ } else {
72
+ throw new Error('All arrays must have an `items` key define');
73
+ }
74
+ };
75
+
76
+ /**
77
+ * Return the output type from an object
78
+ */
79
+ const getObject = (item: SchemaObject): string => {
80
+ if (isReference(item)) {
81
+ return getRef(item.$ref);
82
+ }
83
+
84
+ if (item.allOf) {
85
+ return item.allOf.map(resolveValue).join(' & ');
86
+ }
87
+
88
+ if (item.oneOf) {
89
+ return item.oneOf.map(resolveValue).join(' | ');
90
+ }
91
+
92
+ if (!item.type && !item.properties && !item.additionalProperties) {
93
+ return '{}';
94
+ }
95
+
96
+ // Free form object (https://swagger.io/docs/specification/data-models/data-types/#free-form)
97
+ if (
98
+ item.type === 'object' &&
99
+ !item.properties &&
100
+ (!item.additionalProperties || item.additionalProperties === true || isEmpty(item.additionalProperties))
101
+ ) {
102
+ return '{[key: string]: any}';
103
+ }
104
+
105
+ const IdentifierRegexp = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
106
+ // Consolidation of item.properties & item.additionalProperties
107
+ let output = '{\n';
108
+ if (item.properties) {
109
+ output += Object.entries(item.properties)
110
+ .map(([key, prop]: [string, ReferenceObject | SchemaObject]) => {
111
+ const doc = getDocs(prop);
112
+ const isRequired = (item.required || []).includes(key);
113
+ const processedKey = IdentifierRegexp.test(key) ? key : `"${key}"`;
114
+ return `${doc}\n${processedKey}${isRequired ? '' : '?'}: ${resolveValue(prop)};`;
115
+ })
116
+ .join('');
117
+ }
118
+
119
+ if (item.additionalProperties) {
120
+ if (item.properties) {
121
+ output += '\n';
122
+ }
123
+ output += `} & { [key: string]: ${
124
+ item.additionalProperties === true ? 'any' : resolveValue(item.additionalProperties)
125
+ }`;
126
+ }
127
+
128
+ if (item.properties || item.additionalProperties) {
129
+ if (output === '{\n') {
130
+ return '{}';
131
+ }
132
+ return output + '\n}';
133
+ }
134
+
135
+ return item.type === 'object' ? '{[key: string]: any}' : 'any';
136
+ };
137
+
138
+ /**
139
+ * Resolve the value of a schema object to a proper type definition.
140
+ */
141
+ export const resolveValue = (schema: SchemaObject) =>
142
+ isReference(schema) ? getRef(schema.$ref) : getScalar(schema);
143
+
144
+ /**
145
+ * Format a description to code documentation.
146
+ */
147
+ export const formatDescription = (description?: string) => {
148
+ if (!description) {
149
+ return '';
150
+ }
151
+ return `\n/**\n${description
152
+ .split('\n')
153
+ .map((i) => `* ${i}`)
154
+ .join('\n')}\n */`;
155
+ };
156
+
157
+ /**
158
+ * Extract responses / request types from open-api specs
159
+ */
160
+ export const getResReqTypes = (
161
+ responsesOrRequests: Array<[string, ResponseObject | ReferenceObject | RequestBodyObject]>
162
+ ) => {
163
+ return uniq(
164
+ responsesOrRequests.map(([_, res]) => {
165
+ if (!res) {
166
+ return;
167
+ }
168
+
169
+ if (isReference(res)) {
170
+ return getRef(res.$ref);
171
+ }
172
+
173
+ if (res.content) {
174
+ for (let contentType of Object.keys(res.content)) {
175
+ if (
176
+ contentType.startsWith('application/json') ||
177
+ contentType.startsWith('application/octet-stream')
178
+ ) {
179
+ const schema = res.content[contentType].schema!;
180
+
181
+ return resolveValue(schema);
182
+ }
183
+ }
184
+ return;
185
+ }
186
+
187
+ return;
188
+ })
189
+ ).join(' | ');
190
+ };