-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvalidate.js
117 lines (105 loc) · 2.83 KB
/
validate.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
const fs = require('fs');
const clc = require('chalk');
const request = require('request');
const is = require('./is.js');
const writeResult = require('./report.js').writeResult;
const writeURL = require('./report.js').writeURL;
const argv = require('yargs')
.usage("$0 <url|file> [options]")
.version(false) // Disable default version meaning
.options({ version: { string: true, alias: "v" } })
.default({
"test": false
})
.choices('version', is.versions())
.demandCommand()
.help()
.argv;
const arg = argv['_'][0];
writeURL(arg);
if (arg.startsWith('http')) {
request(arg, (err, res, body) => {
if (!err) {
validate(body);
return;
}
console.error("Request failure for " + arg + ":");
console.log(err);
process.exit(1);
});
} else {
fs.readFile(arg, (err, buff) => {
if (!err) {
validate(buff.toString());
return;
}
console.error("Read failure for " + arg + ":");
console.log(err.message);
process.exit(1);
});
}
function validate(str) {
let parseResult = is.JSONParsable(str);
if (parseResult['error'] == true) {
writeResult(parseResult);
process.exit(1);
}
let json = parseResult['json'];
let version = getVersion(argv, json);
let subSchema = inferSubSchema(json);
if (subSchema === undefined) {
let msg = "Could not infer subschema from JSON.";
let obj = { "error": true, "description": msg, "got": undefined };
writeResult(obj);
process.exit(1);
}
let ignoreVersionError = argv['version'] ? true : false;
if (ignoreVersionError) {
console.log(" " + clc.yellowBright.inverse("⚠") + " Ignoring version in JSON b/c version given on command line.");
}
let jsonResult = is.HAPIJSON(json, version, subSchema, ignoreVersionError);
writeResult(jsonResult);
process.exit(0);
}
function getVersion(argv, json) {
let version = undefined;
if (argv['version']) {
versionResult = is.HAPIVersion(argv['version']);
if (versionResult['error'] == true) {
writeResult(versionResult, 'warn');
process.exit(1);
}
version = argv['version'];
}
if (version === undefined) {
versionResult = is.HAPIVersion(json['HAPI']);
writeResult(versionResult);
if (versionResult['error'] == true) {
process.exit(1);
} else {
version = json['HAPI'];
}
}
return version;
}
function inferSubSchema(json) {
if (json['id']) {
return "about";
}
if (json['outputFormats']) {
return "capabilities";
}
if (json['catalog']) {
return "catalog";
}
if (json['parameters']) {
if (json['data']) {
return "data";
} else {
return "info";
}
}
if (json['status'] && json['status']['code'] >= 1400) {
return "error";
}
}