Blame view

node_modules/ajv-keywords/keywords/instanceof.js 1.3 KB
aaac7fed   liuqimichale   add
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
  'use strict';
  
  var CONSTRUCTORS = {
    Object: Object,
    Array: Array,
    Function: Function,
    Number: Number,
    String: String,
    Date: Date,
    RegExp: RegExp
  };
  
  module.exports = function defFunc(ajv) {
    /* istanbul ignore else */
    if (typeof Buffer != 'undefined')
      CONSTRUCTORS.Buffer = Buffer;
  
    /* istanbul ignore else */
    if (typeof Promise != 'undefined')
      CONSTRUCTORS.Promise = Promise;
  
    defFunc.definition = {
      compile: function (schema) {
        if (typeof schema == 'string') {
          var Constructor = getConstructor(schema);
          return function (data) {
            return data instanceof Constructor;
          };
        }
  
        var constructors = schema.map(getConstructor);
        return function (data) {
          for (var i=0; i<constructors.length; i++)
            if (data instanceof constructors[i]) return true;
          return false;
        };
      },
      CONSTRUCTORS: CONSTRUCTORS,
      metaSchema: {
        anyOf: [
          { type: 'string' },
          {
            type: 'array',
            items: { type: 'string' }
          }
        ]
      }
    };
  
    ajv.addKeyword('instanceof', defFunc.definition);
    return ajv;
  
    function getConstructor(c) {
      var Constructor = CONSTRUCTORS[c];
      if (Constructor) return Constructor;
      throw new Error('invalid "instanceof" keyword value ' + c);
    }
  };