-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate.js
More file actions
90 lines (76 loc) · 2.18 KB
/
validate.js
File metadata and controls
90 lines (76 loc) · 2.18 KB
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
'use strict';
const JSONValidator = require('jsonschema').Validator;
const schema = {
names: require('./schema/names.schema'),
weapons: require('./schema/weapons.schema'),
locations: require('./schema/locations.schema'),
monsters: require('./schema/monsters.schema'),
classes: require('./schema/classes.schema'),
races: require('./schema/races.schema'),
};
/**
* Validate Common outer structure.
*
* @param {object} addon The addon json to validate.
* @return {true}
* @throws Error if outer structure is invalid
*/
function validateOuter(addon) {
if (typeof addon !== 'object') {
throw new TypeError('addon is not an object');
}
['type', 'version', 'data'].forEach((property) => {
if (!addon.hasOwnProperty(property)) {
throw new Error(`addon missing: ${property}`);
}
});
return true;
}
/**
* Validate an addon's schema.
*
* @param {object} addon The addon json to validate.
* @return {true}
* @throws Error if names structure is invalid
*/
function validateSchema(addon) {
validateOuter(addon);
if (!schema.hasOwnProperty(addon.type)) {
throw new Error(`Unknown Schema Type: ${addon.type}`);
}
if (!schema[addon.type].hasOwnProperty(addon.version)) {
throw new Error(`Unknown Schema Version: ${addon.version}`);
}
let v = new JSONValidator();
let validateResult = v.validate(addon.data, schema[addon.type][addon.version]);
if (validateResult.errors.length > 0) {
const combinedErrors = validateResult.errors.reduce((prev, current) => {
return prev.concat([current.message]);
}, []);
throw new Error(`Schema Validation Errors:\n${combinedErrors.join('\n')}`);
}
return true;
}
/**
* Normalize, Detect Version, and Validate addon.
*
* @param {object|string} addon The json string/object to check
* @return {true}
* @throws Error if it cannot decode json or any validation events occur
*/
function check(addon) {
if (typeof addon !== 'object') {
try {
addon = JSON.parse(addon);
} catch (error) {
throw new Error(`Could not decode string into JSON. Error: ${error.message}`);
}
}
return validateSchema(addon);
}
module.exports = {
schema,
validateOuter,
validateSchema,
check,
};