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