parameter-validator.js
2.5 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
91
92
93
'use strict';
var cJSON = require('circular-json')
, _ = require('lodash'); // Don't require Utils here, as it creates a circular dependency
var extractClassName = function(o) {
if (typeof o === 'string') {
return o;
} else if (!!o) {
return o.toString().match(/function ([^\(]+)/)[1];
} else {
return 'undefined';
}
};
var generateDeprecationWarning = function(value, expectation, options) {
options = options || {};
if (options.method && options.index) {
return [
'The',
{1: 'first', 2: 'second', 3: 'third', 4: 'fourth', 5: 'fifth'}[options.index],
'parameter of',
options.method,
'should be a',
extractClassName(expectation) + '!'
].join(' ');
} else {
return ['Expected', cJSON.stringify(value), 'to be', extractClassName(expectation) + '!'].join(' ');
}
};
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 = extractClassName(expectation);
throw new Error('The parameter (value: ' + _value + ') is no ' + _expectation + '.');
}
};
var ParameterValidator = module.exports = {
check: function(value, expectation, options) {
options = _.extend({
throwError: true,
deprecated: false,
deprecationWarning: generateDeprecationWarning(value, expectation, options),
onDeprecated: function(s) { console.log('DEPRECATION WARNING:', s); },
index: null,
method: null,
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);
}
};