-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate-api-types.js
More file actions
219 lines (182 loc) · 5.51 KB
/
generate-api-types.js
File metadata and controls
219 lines (182 loc) · 5.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import 'dotenv/config';
import fs from 'fs';
import path from 'path';
import { generateApi } from 'swagger-typescript-api';
import { parse as $RefParser } from '@apidevtools/json-schema-ref-parser';
const backendUrl = process.env.VITE_SERVER_URL;
const swaggerUrl = backendUrl + '/docs.json';
const outputDir = path.resolve(process.cwd(), 'src/api/types');
function getAllSchemaRefs(obj, refs = new Set()) {
if (typeof obj !== 'object' || obj === null) return refs;
if (Array.isArray(obj)) {
for (const item of obj) {
getAllSchemaRefs(item, refs);
}
return refs;
}
for (const key in obj) {
const value = obj[key];
if (
key === '$ref' &&
typeof value === 'string' &&
value.startsWith('#/components/schemas/')
) {
const refName = value.split('/').pop();
if (refName && !refs.has(refName)) {
refs.add(refName);
}
} else {
getAllSchemaRefs(value, refs);
}
}
return refs;
}
function removeSwaggerHeader(filePath) {
if (!fs.existsSync(filePath)) return;
let content = fs.readFileSync(filePath, 'utf8');
content = content.replace(
/\/\*[\s\S]*?## SOURCE: https:\/\/github\.com\/acacode\/swagger-typescript-api ##[\s\S]*?\*\/\s*/,
''
);
fs.writeFileSync(filePath, content);
}
function extractVersionFromPath(pathKey) {
const versionMatch = pathKey.match(/^\/(v[0-9]+)/i);
return versionMatch?.[1] ?? 'unversioned';
}
function buildTagVersionMap(rawSpec) {
const tagMap = new Map();
Object.entries(rawSpec.paths).forEach(([pathKey, methods]) => {
const pathVersion = extractVersionFromPath(pathKey);
Object.values(methods)
.filter((method) => method?.tags)
.forEach((method) => {
method.tags.forEach((tag) => {
if (!tagMap.has(tag)) tagMap.set(tag, new Set());
tagMap.get(tag).add(pathVersion);
});
});
});
return tagMap;
}
function filterSpecByTagAndVersion(spec, tag, version) {
const filteredSpec = JSON.parse(JSON.stringify(spec));
Object.entries(filteredSpec.paths).forEach(([pathKey, methods]) => {
const pathVersion = extractVersionFromPath(pathKey);
if (pathVersion !== version) {
delete filteredSpec.paths[pathKey];
return;
}
const filteredMethods = Object.fromEntries(
Object.entries(methods).filter(([, method]) =>
method?.tags?.includes(tag)
)
);
if (Object.keys(filteredMethods).length === 0) {
delete filteredSpec.paths[pathKey];
} else {
filteredSpec.paths[pathKey] = filteredMethods;
}
});
return filteredSpec;
}
function filterSchemas(spec) {
const allSchemas = spec.components?.schemas || {};
const allUsedSchemas = new Set();
function collectAllRefs(schemaName) {
if (!schemaName || allUsedSchemas.has(schemaName)) return;
allUsedSchemas.add(schemaName);
const schema = allSchemas[schemaName];
if (!schema) return;
const refs = getAllSchemaRefs(schema);
for (const ref of refs) {
collectAllRefs(ref);
}
}
const directRefs = getAllSchemaRefs(spec.paths);
for (const schemaName of directRefs) {
collectAllRefs(schemaName);
}
const filteredSchemas = Object.fromEntries(
Object.entries(allSchemas).filter(([schemaName]) =>
allUsedSchemas.has(schemaName)
)
);
return {
...spec,
components: {
...spec.components,
schemas: filteredSchemas,
},
};
}
function ensureDirectoryExists(dirPath) {
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
}
}
function cleanOutputDirectory() {
if (fs.existsSync(outputDir)) {
fs.rmSync(outputDir, { recursive: true, force: true });
}
}
async function generateTypeFile(spec, tag, version, versionDir) {
const tagFileName = `${tag.toLowerCase()}.type.ts`;
const tagFilePath = path.join(versionDir, tagFileName);
await generateApi({
name: tagFileName,
output: versionDir,
httpClientType: 'fetch',
spec,
modular: false,
generateClient: false,
cleanOutput: false,
});
const possiblePaths = [
path.join(versionDir, 'index.ts'),
path.join(versionDir, 'Api.ts'),
];
for (const possiblePath of possiblePaths) {
if (fs.existsSync(possiblePath)) {
if (fs.existsSync(tagFilePath)) fs.unlinkSync(tagFilePath);
fs.renameSync(possiblePath, tagFilePath);
break;
}
}
removeSwaggerHeader(tagFilePath);
return `[GENERATED]: ${version}/${tagFileName}`;
}
async function fetchSpecs() {
const dereferencedSpec = await $RefParser(swaggerUrl);
return { dereferencedSpec };
}
async function main() {
try {
if (!backendUrl) throw new Error('[ENV ERROR]:VITE_SERVER_URL not defined');
cleanOutputDirectory();
const { dereferencedSpec } = await fetchSpecs();
const tagMap = buildTagVersionMap(dereferencedSpec);
const generatedFiles = [];
for (const [tag, versions] of tagMap.entries()) {
const versionFiles = await Promise.all(
Array.from(versions).map(async (version) => {
const versionDir = path.join(outputDir, version);
ensureDirectoryExists(versionDir);
let filteredSpec = filterSpecByTagAndVersion(
dereferencedSpec,
tag,
version
);
filteredSpec = filterSchemas(filteredSpec);
return await generateTypeFile(filteredSpec, tag, version, versionDir);
})
);
generatedFiles.push(...versionFiles);
}
console.log(generatedFiles.join('\n'));
} catch (error) {
console.error('[ERROR]', error);
process.exit(1);
}
}
main();