-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.js
103 lines (85 loc) · 2.35 KB
/
index.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
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
94
95
96
97
98
99
100
101
102
103
module.exports = function(ajv) {
const type = function(v) {
if (v === null) {
return 'null';
}
if (v === undefined) {
return 'undefined';
}
const s = Object.prototype.toString.call(v);
const t = s.match(/\[object (.*?)\]/)[1].toLowerCase();
if (t === 'number') {
if (isNaN(v)) {
return 'nan';
}
if (!isFinite(v)) {
return 'infinity';
}
}
return t;
};
const $type = function(a) {
const t = type(a);
const checkBsonType = b => (t === 'object') && (a._bsontype === b);
return function(b) {
switch (b) {
case 1: case 'double':
return (t === 'number') && ((a + '').indexOf('.') !== -1);
case 2: case 'string':
return t === 'string';
case 3: case 'object':
return t === 'object';
case 4: case 'array':
return t === 'array';
case 6: case 'undefined':
return [ 'null', 'undefined' ].includes(t);
case 7: case 'objectId':
return checkBsonType('ObjectID');
case 8: case 'bool': case 'boolean':
return t === 'boolean';
case 9: case 'date':
return t === 'date';
case 10: case 'null':
return t === 'null';
case 11: case 'regex':
return t === 'regex';
case 16: case 'int':
return (t === 'number') && (a <= 2147483647) && ((a + '').indexOf('.') === -1);
case 18: case 'long':
return (t === 'number') && (a > 2147483647) && (a <= 9223372036854775807) && ((a + '').indexOf('.') === -1);
case 19: case 'decimal':
return checkBsonType('Decimal128');
case 20: case 'number':
return t === 'number';
default: return false;
}
};
};
var validate = (schema, data) => {
if (validate.errors === null)
validate.errors = [];
const v = $type(data);
let msg, passed;
if (Array.isArray(schema)) {
msg = schema.join(', ');
passed = schema.some(v);
} else {
msg = schema;
passed = v(schema);
}
if (!passed) {
validate.errors.push({
keyword: 'bsonType',
params: {
bsonType: schema
},
message: `should be ${msg} got ${data}`
});
}
return passed;
};
ajv.addKeyword('bsonType', {
errors: true,
validate
});
};