parameter-validator.js
1.63 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
var ParameterValidator = module.exports = {
check: function(value, expectation, options) {
options = Utils._.extend({
throwError: true,
deprecated: false,
deprecationWarning: "Deprecated!",
onDeprecated: function(s){ console.log('DEPRECATION WARNING:', s) },
optional: false
}, options || {})
if (options.optional && ((value === undefined) || (value === null)) ) {
return true
}
if (value === undefined) {
throw new Error('No value has been passed.')
}
if (expectation === undefined) {
throw new Error('No expectation has been passed.')
}
return false
|| validateDeprication(value, expectation, options)
|| validate(value, expectation, options)
}
}
var matchesExpectation = function(value, expectation) {
if (typeof expectation === 'string') {
return (typeof value === expectation.toString())
} else {
return (value instanceof expectation)
}
}
var validateDeprication = function(value, expectation, options) {
if (options.deprecated) {
if (matchesExpectation(value, options.deprecated)) {
options.onDeprecated(options.deprecationWarning)
return true
}
}
}
var validate = function(value, expectation, options) {
var result = matchesExpectation(value, expectation)
if (result) {
return result
} else if (!options.throwError) {
return false
} else {
var _value = (value === null) ? 'null' : value.toString()
, _expectation = expectation.toString().match(/function ([^\(]+)/)[1]
throw new Error('The parameter (value: ' + _value + ') is no ' + _expectation + '.')
}
}