-
Notifications
You must be signed in to change notification settings - Fork 5
/
type-checks.js
61 lines (54 loc) · 1.59 KB
/
type-checks.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
/**
* DRY function for checking if passed value is of expected type.
*
* @param {string} name Name of setting to check
* @param {object} value Value to check
* @param {string} type Type to match
* @param {string} errorPrefix String to prepend thrown error with
* @returns {bool}
* @throws {TypeError}
*/
function checkType(name, value, type, errorPrefix) {
if (type === 'array' && !Array.isArray(value)) {
throw new TypeError(`${errorPrefix} configuration setting '${name}' not of type '${type}'`);
}
// eslint-disable-next-line valid-typeof
if (type !== 'array' && typeof value !== type) {
throw new TypeError(`${errorPrefix} configuration setting '${name}' not of type '${type}'`);
}
return true;
}
/**
* Checks if optional value is of expected type.
*
* @param {string} name Object to check
* @param {object} value Object to check
* @param {string} type Property type
* @returns {bool}
* @throws {TypeError}
*/
const checkTypeOptional = function check(name, value, type) {
if (value === null) {
return true;
}
return checkType(name, value, type, 'Optional');
};
/**
* Checks if required value is of expected type.
*
* @param {string} name Object to check
* @param {object} value Object to check
* @param {string} type Property type
* @returns {bool}
* @throws {TypeError}
*/
const checkTypeRequired = function check(name, value, type) {
if (value === null) {
throw new TypeError(`Required configuration setting '${name}' is missing`);
}
return checkType(name, value, type, 'Required');
};
module.exports = {
checkTypeOptional,
checkTypeRequired,
};