You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

instanceof.js 1.3KB

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