-
Notifications
You must be signed in to change notification settings - Fork 1
/
parsers.js
85 lines (83 loc) · 2.78 KB
/
parsers.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
function parseArray(value){
if (!value) return [];
if (Array.isArray(value)) return value;
if (typeof(value) === "string") return value.split("\n").map(line=>line.trim()).filter(line=>line);
throw "Unsupprted array format";
}
module.exports = {
boolean : (value) =>{
if (!value || value === "false") return false;
return true;
},
text : (value) =>{
if (value)
return value.split('\n');
return undefined;
},
number: (value)=>{
if (!value) return undefined;
const parsed = parseInt(value);
if (parsed === NaN) {
throw `Value ${value} is not a valid number`
}
return parsed;
},
autocomplete: (value, getVal)=>{
if (!value) return undefined;
if (typeof(value) == "object") return (getVal ? value.value : value.id) || value;
return value;
},
autocompleteOrArray: (value)=>{
if (!value) return [];
if (Array.isArray(value)) return value;
if (typeof(value) == "object") return [value.id || value];
return [value];
},
tags: (value, letKeyOnly)=>{
if (!value) return undefined;
if (typeof(value) == "string") {
const obj = {};
value.split("\n").forEach((line) => {
let [key, ...val] = line.trim().split("=");
if (!key || (!letKeyOnly && !val)) throw "bad labels/tags format";
if (val.length) obj[key] = val.join("=");
else obj[key] = "";
});
return obj;
}
throw `Value ${value} is not a valid tags/labels input.`;
},
json: (value)=>{
if (!value) return undefined;
if (typeof(value) === "object") return value;
if (typeof(value) == "string") {
value = value.trim();
if (value.startsWith("{") && value.endsWith("}")){
try {
return JSON.parse(value);
}
catch (e) {
throw `Invalid JSON! ` + e.message;
}
}
else {
if (!fs.existsSync(value)) throw `Couldn't find file '${value}'.`;
const fileContent = fs.readFileSync(value, 'utf8');
try {
const obj = JSON.parse(fileContent);
return obj;
}
catch {
throw `The file '${value}' doesn't contain a valid JSON.`
}
}
}
throw `Value ${value} is not a valid JSON input.`;
},
string: (value)=>{
if (!value) return undefined;
if (typeof(value) === "string") return value.trim();
throw `Value ${value} is not a valid string`;
},
array: parseArray
}