-
Notifications
You must be signed in to change notification settings - Fork 7
/
normalize.js
71 lines (62 loc) · 1.96 KB
/
normalize.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
const _ = require('./helper');
const I18N = require('./I18N');
const Normalize = {
fields(fields) {
let parts = ['extensions', 'metadata', 'links', 'assets'];
for (let part of parts) {
for(let key in fields[part]) {
fields[part][key] = Normalize.field(fields[part][key], fields[part], fields);
}
}
return fields;
},
field(spec, fields = {}, allFields = {}) {
// If just a string label is given, make a normal object with a label from it
if (typeof spec === 'string') {
return {
label: spec
};
}
// Resolve alias
if (typeof spec.alias === 'string') {
// As we don't know whether the alias has been resolved so far, resolve it here, too.
let aliasedSpec = fields[spec.alias] || allFields.metadata[spec.alias];
if (!aliasedSpec) {
throw new Error('Alias is invalid: ' + spec.alias);
}
return Object.assign(spec, Normalize.field(aliasedSpec, fields, allFields));
}
// Normalize items
if (_.isObject(spec.items)) {
let itemOrder = [];
for(let key in spec.items) {
spec.items[key] = Normalize.field(spec.items[key], fields, allFields);
itemOrder.push(Object.assign({key}, spec.items[key]));
}
spec.itemOrder = itemOrder
.sort((i1, i2) => {
if (i1.id === true) {
return -1;
}
else if (i2.id === true) {
return 1;
}
else if (typeof i1.order === 'number' && typeof i2.order === 'number') {
return i1.order - i2.order;
}
else {
return I18N.collator.compare(_.t(i1.label), _.t(i2.label));
}
})
.map(item => item.key);
}
// Normalize properties
if (_.isObject(spec.properties)) {
for(let key in spec.properties) {
spec.properties[key] = Normalize.field(spec.properties[key], fields, allFields);
}
}
return spec;
}
};
module.exports = Normalize;