-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathget-and-modify-oas-for-csharp.js
99 lines (83 loc) · 2.95 KB
/
get-and-modify-oas-for-csharp.js
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
const fs = require('node:fs');
async function prefixOpenApiSchema(url, prefix, outputFile) {
try {
// Download the JSON file using fetch
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const openApiSpec = await response.json();
// Modify schemas and references
if (openApiSpec.components?.schemas) {
const schemas = openApiSpec.components.schemas;
const modifiedSchemas = {};
for (const [key, value] of Object.entries(schemas)) {
const newKey = `${prefix}${key}`;
modifiedSchemas[newKey] = value;
// Update references within the schema
const schemaString = JSON.stringify(value);
const updatedSchemaString = schemaString.replace(
/#\/components\/schemas\/(\w+)/g,
`#/components/schemas/${prefix}$1`,
);
modifiedSchemas[newKey] = JSON.parse(updatedSchemaString);
}
openApiSpec.components.schemas = modifiedSchemas;
}
// Update references in paths
if (openApiSpec.paths) {
const paths = openApiSpec.paths;
for (const path in paths) {
const methods = paths[path];
for (const method in methods) {
const operation = methods[method];
if (operation.requestBody?.content) {
updateContentReferences(operation.requestBody.content, prefix);
}
if (operation.responses) {
for (const response in operation.responses) {
const content = operation.responses[response].content;
if (content) {
updateContentReferences(content, prefix);
}
}
}
if (operation.parameters) {
operation.parameters.forEach((parameter) => {
if (parameter.schema?.$ref) {
parameter.schema.$ref = parameter.schema.$ref.replace(
/#\/components\/schemas\/(\w+)/g,
`#/components/schemas/${prefix}$1`,
);
}
});
}
}
}
}
// Write the modified JSON to a file
fs.writeFileSync(outputFile, JSON.stringify(openApiSpec, null, 2));
console.info(`Modified Open API specification saved to ${outputFile}`);
} catch (error) {
console.error(error);
}
}
function updateContentReferences(content, prefix) {
for (const type in content) {
if (content[type].schema?.$ref) {
content[type].schema.$ref = content[type].schema.$ref.replace(
/#\/components\/schemas\/(\w+)/g,
`#/components/schemas/${prefix}$1`,
);
}
}
}
// Example usage:
// node prefixOpenApi.js 'https://example.com/openapi.json' 'MyPrefix' 'output.json'
const args = process.argv.slice(2);
if (args.length !== 3) {
console.error('Usage: node prefixOpenApi.js <url> <prefix> <outputFile>');
process.exit(1);
}
const [url, prefix, outputFile] = args;
prefixOpenApiSchema(url, prefix, outputFile);