-
Notifications
You must be signed in to change notification settings - Fork 0
/
codegen.js
150 lines (123 loc) · 4.62 KB
/
codegen.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
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
const yaml = require('js-yaml');
const fs = require('fs');
const path = require('path');
const schemaRoot = './openapi/schema.yaml';
const destination = './src/'
const openapiFile = fs.readFileSync(schemaRoot, 'utf8');
const openapiSchema = yaml.load(openapiFile);
const classes = generateClasses(parseModelSchema(openapiSchema));
const methods = parseMethodSchema(openapiSchema);
// Generate JavaScript classes
const jsClasses = classes.concat(methods);
// Write the generated classes to a file
fs.writeFileSync(destination.concat("apiclient.js"), jsClasses);
console.log('JavaScript classes generated successfully!');
function parseMethodSchema(fullSchema) {
let classes = `
async function fetchData(url, params, factoryFn, token) {
try {
// Construct query string from params
const queryString = new URLSearchParams(params).toString();
const fullUrl = \`\${url}?\${queryString}\`;
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': \`Bearer \${token}\`
}
});
if (response.status === 418) {
throw new Error(response.headers.get("Error-Message"));
}
const responseData = await response.json();
const returnedData = factoryFn(responseData);
console.log('Successful registration:', returnedData);
return returnedData;
} catch (error) {
console.error('Error:', error);
throw new Error(error.message)
}
}
async function postData(url, data, factoryFn, token) {
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': \`Bearer \${token}\`
},
body: JSON.stringify(data)
});
if (response.status === 418) {
throw new Error(response.headers.get("Error-Message"));
}
const responseData = await response.json();
const returnedData = factoryFn(responseData);
console.log('Successful registration:', returnedData);
return returnedData;
} catch (error) {
console.error('Error:', error);
throw new Error(error.message)
}
}
`;
let serverUrl = fullSchema.servers[0].url;
for (const [path, methods] of Object.entries(fullSchema.paths)) {
for (const [method, details] of Object.entries(methods)) {
const methodName = details.summary.replace(/\s+/g, '');
let factoryFn = "(data) => (data)";
if(details.responses && details.responses['200'] && details.responses['200'].content) {
let className = details.responses['200'].content['application/json'].schema.$ref.split('/').pop();
factoryFn = `(data) => Object.assign(new ${className}(), data)`;
}
if (method.toUpperCase() === 'GET') {
classes += `
export async function ${methodName}(token = "", params = {}) {
return fetchData(\`${serverUrl}${path}\`, params, ${factoryFn}, token);
}\n`;
} else if (method.toUpperCase() === 'POST') {
classes += `
export async function ${methodName}(data, token = "") {
return postData(\`${serverUrl}${path}\`, data, ${factoryFn}, token);
}\n`;
}
}
}
return classes;
}
function parseModelSchema(fullSchema) {
let schemas = {};
for (const [name, schemaRef] of Object.entries(fullSchema.components.schemas)) {
if (schemaRef.$ref) {
let refSchema = loadSchema(schemaRef.$ref);
schemas[name] = refSchema;
} else {
schemas[name] = schemaRef;
}
}
return schemas;
}
function loadSchema(ref) {
const refPath = path.join(path.dirname(schemaRoot), ref);
const schemaFile = fs.readFileSync(refPath, 'utf8');
return yaml.load(schemaFile);
}
function generateClasses(schemas) {
let classes = '/** Do not edit this file. It is autogenerated **/\n\n';
for (const [className, schema] of Object.entries(schemas)) {
if (schema.type === 'object' && schema.properties) {
classes += `export class ${className} {\n`;
classes += ' constructor(data = {}) {\n';
for (const [propName, propDef] of Object.entries(schema.properties)) {
if(propDef.$ref) {
classes += ` this.${propName} = data['${propName}']? data['${propName}'] : new ${propDef.$ref.split("/").pop().replace(".yaml", "")}();\n`;
} else {
classes += ` this.${propName} = data['${propName}']? data['${propName}'] : undefined ;\n`;
}
}
classes += ' }\n';
classes += '}\n\n';
}
}
return classes;
}