forked from n3ps/json-schema-to-jsdoc
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
85 lines (67 loc) · 2.16 KB
/
index.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
const fs = require('fs');
const json = require('json-pointer');
module.exports = generate;
function generate(schema, options = {}) {
let jsdoc = '';
if (!schema || Object.keys(schema).length === 0) {
return jsdoc;
}
jsdoc += '/**\n';
jsdoc += writeDescription(schema);
if (!json.has(schema, '/properties')){
return jsdoc;
}
jsdoc += processProperties(schema, false, options);
jsdoc += ' */\n';
return jsdoc;
}
function processProperties(schema, nested, options = {}) {
const props = json.get(schema, '/properties');
const required = json.has(schema, '/required') ? json.get(schema, '/required') : [];
let text = '';
for (let property in props) {
if (Array.isArray(options.ignore) && options.ignore.includes(property)) {
continue;
} else {
let prefix = nested ? '.' : '';
if (props[property].type === 'object' && props[property].properties) {
text += writeParam('object', prefix + property, props[property].description, true);
text += processProperties(props[property], true);
} else {
let optional = !required.includes(property);
let type = getType(props[property]) || upperFirst(property);
text += writeParam(type, prefix + property, props[property].description, optional);
}
}
}
return text;
}
function writeDescription(schema, suffix = 'object') {
let text = schema.description || `Represents a ${schema.id} ${suffix}`;
text += `\n * @name ${upperFirst(schema.id)}`;
return ` * ${text}\n *\n`;
}
function writeParam(type = '', field, description = '', optional) {
const fieldTemplate = optional ? `[${field}]` : field;
return ` * @property {${type}} ${fieldTemplate} - ${description} \n`;
}
function getType(schema) {
if (schema.$ref) {
const ref = json.get(root, schema.$ref.substr(1));
return getType(ref);
}
if (schema.enum) {
return 'enum';
}
if (Array.isArray(schema.type)) {
if (schema.type.includes('null')) {
return `?${schema.type[0]}`;
} else {
return schema.type.join('|');
}
}
return schema.type;
}
function upperFirst(str = '') {
return str.substr(0,1).toUpperCase() + str.substr(1);
}