react-query-lightbase-codegen 1.1.0 → 1.1.1

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,39 @@
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 { generateImports, generateQueryHooks } from './generateHooks.js';
6
+ import { generateSchemas } from './generateSchemas.js';
7
+ export function importSpecs({ sourceDirectory, exportDirectory, apiDirectory, queryClientDir, headerFilters, }) {
8
+ readdir(sourceDirectory, function (err, filenames) {
9
+ if (err) {
10
+ console.log(err);
11
+ throw err;
12
+ }
13
+ filenames.map(async (filename) => {
14
+ try {
15
+ const data = readFileSync(join(process.cwd(), sourceDirectory + '/' + filename), 'utf-8');
16
+ const { ext } = parse(sourceDirectory + '/' + filename);
17
+ const format = ['.yaml', '.yml'].includes(ext.toLowerCase()) ? 'yaml' : 'json';
18
+ const name = filename.split('.')[0];
19
+ let spec = await convertSwaggerFile(data, format);
20
+ const operationIds = [];
21
+ mkdirSync(join(process.cwd(), `${exportDirectory}/${name}`), { recursive: true });
22
+ const { implementation, schemaImports } = generateQueryHooks({ spec, operationIds, headerFilters });
23
+ const schemaName = `useQueries${filename.split('.')[0]}.schema`;
24
+ const imports = generateImports({ apiDirectory, queryClientDir, schemaName, schemaImports });
25
+ const hooksName = `useQueries${filename.split('.')[0]}`;
26
+ writeFileSync(join(process.cwd(), `${exportDirectory}/${name}/${hooksName}.tsx`), imports + implementation);
27
+ const schemas = generateSchemas({ spec });
28
+ writeFileSync(join(process.cwd(), `${exportDirectory}/${name}/${schemaName}.tsx`), schemas);
29
+ console.log(chalk.green(`🎉 [${filename}] Your OpenAPI spec has been converted into react query hooks`));
30
+ }
31
+ catch (error) {
32
+ if (error.code === 'EISDIR') {
33
+ return;
34
+ }
35
+ console.log(chalk.red(`[${filename}]:`), chalk.red(error));
36
+ }
37
+ });
38
+ });
39
+ }
@@ -0,0 +1,3 @@
1
+ import { convertSwaggerFile } from './convertSwaggerFile.js';
2
+ import { importSpecs } from './importSpecs.js';
3
+ export { importSpecs, convertSwaggerFile };
@@ -0,0 +1,153 @@
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
+ return `/**\n${description
128
+ .split('\n')
129
+ .map((i) => `* ${i}`)
130
+ .join('\n')}\n */`;
131
+ };
132
+ /**
133
+ * Extract responses / request types from open-api specs
134
+ */
135
+ export const getResReqTypes = (responsesOrRequests) => uniq(responsesOrRequests.map(([_, res]) => {
136
+ if (!res) {
137
+ return;
138
+ }
139
+ if (isReference(res)) {
140
+ return getRef(res.$ref);
141
+ }
142
+ if (res.content) {
143
+ for (let contentType of Object.keys(res.content)) {
144
+ if (contentType.startsWith('application/json') ||
145
+ contentType.startsWith('application/octet-stream')) {
146
+ const schema = res.content[contentType].schema;
147
+ return resolveValue(schema);
148
+ }
149
+ }
150
+ return;
151
+ }
152
+ return;
153
+ })).join(' | ');
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "react-query-lightbase-codegen",
3
3
  "description": "Fully typed react query code generation tool based on openApi specifications",
4
- "version": "1.1.0",
4
+ "version": "1.1.1",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
- "exports": "./dist/index.js",
7
+ "exports": "./lib/index.js",
8
8
  "files": [
9
9
  "src",
10
- "dist"
10
+ "lib"
11
11
  ],
12
12
  "keywords": [
13
13
  "rest",
@@ -29,7 +29,7 @@
29
29
  },
30
30
  "repository": {
31
31
  "type": "git",
32
- "url": "https://github.com/owinter86/react-query-codegen"
32
+ "url": "https://github.com/lightbasenl/react-query-codegen"
33
33
  },
34
34
  "engines": {
35
35
  "node": ">=14.16"