UNPKG

1.23 kBJavaScriptView Raw
1'use strict';
2
3var CONSTRUCTORS = {
4 Object: Object,
5 Array: Array,
6 Function: Function,
7 Number: Number,
8 String: String,
9 Date: Date,
10 RegExp: RegExp
11};
12
13module.exports = function defFunc(ajv) {
14 /* istanbul ignore else */
15 if (typeof Buffer != 'undefined')
16 CONSTRUCTORS.Buffer = Buffer;
17
18 defFunc.definition = {
19 compile: function (schema) {
20 if (typeof schema == 'string') {
21 var Constructor = getConstructor(schema);
22 return function (data) {
23 return data instanceof Constructor;
24 };
25 }
26
27 var constructors = schema.map(getConstructor);
28 return function (data) {
29 for (var i=0; i<constructors.length; i++)
30 if (data instanceof constructors[i]) return true;
31 return false;
32 };
33 },
34 CONSTRUCTORS: CONSTRUCTORS,
35 metaSchema: {
36 anyOf: [
37 { type: 'string' },
38 {
39 type: 'array',
40 items: { type: 'string' }
41 }
42 ]
43 }
44 };
45
46 ajv.addKeyword('instanceof', defFunc.definition);
47 return ajv;
48
49 function getConstructor(c) {
50 var Constructor = CONSTRUCTORS[c];
51 if (Constructor) return Constructor;
52 throw new Error('invalid "instanceof" keyword value ' + c);
53 }
54};