-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
95 lines (92 loc) · 2.88 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
86
87
88
89
90
91
92
93
94
95
class Json2JSDoc {
/**
* @param {object} input
* @param {string} namespace
* @param {string} memberOf
* @param {string} break_line
* @param {boolean} add_content_as_description
*/
constructor(input, {namespace = 'Default', memberOf, break_line = '\n', add_content_as_description = false} = {}) {
if (typeof input !== 'object') throw new Error(`Only support object as input`);
this.input = Array.isArray(input) ? input[0] : input;
this.namespace = namespace;
this.memberOf = memberOf === '' ? null: memberOf;
this.break_line = break_line;
this.add_content_as_description = add_content_as_description;
this.json_list = [];
}
/**@private*/
static correctNamespace(namespace) {
return namespace.replace(/[^a-zA-Z0-9_]/g, '_');
}
/**
* @return {typeof Json2JSDoc}
*/
convert({input = this.input, namespace = this.namespace, memberOf = this.memberOf}={}) {
const body = Object.keys(input).map(key=>{
const is_array = Array.isArray(input[key]);
const value = is_array ? input[key][0] : input[key];
const value_type = typeof value;
switch (value_type) {
case "undefined":
return {
type: '*',
name: key,
is_array
};
case "number":
case "string":
case "boolean":
case "function":
return {
type: value_type,
name: key,
is_array,
value: JSON.stringify(value)
};
case "object":
if (value == null) {
return {
type: 'null|*',
name: key
}
}
this.convert({
input: value,
namespace: this.constructor.correctNamespace(key),
memberOf: `${memberOf == null ? '' : `${memberOf}.`}${namespace}`
});
return {
type: `${memberOf == null ? '' : `${memberOf}.`}${namespace}.${this.constructor.correctNamespace(key)}`,
is_array,
name: key
};
default:
console.warn(`New value type '${value_type}'`)
}
});
this.json_list.unshift({
namespace,
memberOf,
body
});
return this;
}
export() {
return this.json_list.map(({namespace, memberOf, body}) => {
const jsdoc = [];
jsdoc.push(`/** @namespace ${namespace}`);
if (memberOf != null) jsdoc.push(` * @memberOf ${memberOf}`);
body.forEach(({type, name, is_array, value}) => {
if (value != null && this.add_content_as_description) {
jsdoc.push(` * @property {${type}${is_array === true?'[]':''}} ${name} - ${value}`);
} else {
jsdoc.push(` * @property {${type}${is_array === true?'[]':''}} ${name}`);
}
});
jsdoc.push(' */');
return jsdoc.join(this.break_line);
}).join(this.break_line);
}
}
module.exports = Json2JSDoc;