-
Notifications
You must be signed in to change notification settings - Fork 285
/
Copy pathformatter.js
60 lines (52 loc) · 1.8 KB
/
formatter.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
const _ = require('lodash');
/**
* Format the responses for the APIs
* @param data - initial data, that should have all of the necessary methods and schemas
* @returns {object}
*/
function format(data) {
const { methods, definitions } = data;
// check if there are none
if (!(methods && methods.length > 0 && definitions && definitions.length > 0)) {
throw new Error('Methods and definitions should not be empty!');
}
const mutable = _.cloneDeep(data);
// get definitions based on $ref
methods.forEach((method, i) => {
const list = Object.keys(method.responses);
const formatted = {};
if (list.length > 0) {
list.forEach((response) => {
formatted[response] = method.responses[response];
const refName = formatted[response].schema['$ref'].split('/').slice(-1)[0];
definitions.forEach((definition) => {
if (refName === definition.name) {
formatted[response].properties = definition.tsType.properties;
formatted[response].status = Number(response) || null;
}
});
});
}
// generate the code
list.forEach((response) => {
let code = `return res.code(${formatted[response].status}).send({`;
formatted[response].properties.forEach((property, i) => {
// remove the whitespaces from the parameter names
const name = property.name.replace(/\s/g, '');
formatted[response].properties[i].name = name;
// escape the quoutes
const value = property.tsType === 'string' ? '"string"' : 0;
code = `${code}
${name}: ${value},`;
});
formatted[response].code = `${code}
});`;
});
// add the code to the resulting object
mutable.methods[i].responses = formatted;
});
return mutable;
}
module.exports = {
format,
};