parameter-validator.js
1.56 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
'use strict';
var _ = require('lodash');
var util = require('util');
function validateDeprecation (value, expectation, options) {
if (!options.deprecated) {
return;
}
var valid = value instanceof options.deprecated || Object.prototype.toString.call(value) === Object.prototype.toString.call(options.deprecated.call());
if (valid) {
var message = util.format('%s should not be of type "%s"', util.inspect(value), options.deprecated.name);
console.log('DEPRECATION WARNING:', options.deprecationWarning || message);
}
return valid;
}
function validate (value, expectation) {
// the second part of this check is a workaround to deal with an issue that occurs in node-webkit when
// using object literals. https://github.com/sequelize/sequelize/issues/2685
if (value instanceof expectation || Object.prototype.toString.call(value) === Object.prototype.toString.call(expectation.call())) {
return true;
}
throw new Error(util.format('The parameter (value: %s) is no %s.', value, expectation.name));
}
function check (value, expectation, options) {
options = _.extend({
deprecated: false,
index: null,
method: null,
optional: false
}, options || {});
if (!value && options.optional) {
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
|| validateDeprecation(value, expectation, options)
|| validate(value, expectation, options);
}
module.exports = check;