boolean.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /*!
  2. * Module dependencies.
  3. */
  4. var utils = require('../utils');
  5. var SchemaType = require('../schematype');
  6. var utils = require('../utils');
  7. /**
  8. * Boolean SchemaType constructor.
  9. *
  10. * @param {String} path
  11. * @param {Object} options
  12. * @inherits SchemaType
  13. * @api private
  14. */
  15. function SchemaBoolean (path, options) {
  16. SchemaType.call(this, path, options, 'Boolean');
  17. }
  18. /**
  19. * This schema type's name, to defend against minifiers that mangle
  20. * function names.
  21. *
  22. * @api private
  23. */
  24. SchemaBoolean.schemaName = 'Boolean';
  25. /*!
  26. * Inherits from SchemaType.
  27. */
  28. SchemaBoolean.prototype = Object.create( SchemaType.prototype );
  29. SchemaBoolean.prototype.constructor = SchemaBoolean;
  30. /**
  31. * Required validator
  32. *
  33. * @api private
  34. */
  35. SchemaBoolean.prototype.checkRequired = function (value) {
  36. return value === true || value === false;
  37. };
  38. /**
  39. * Casts to boolean
  40. *
  41. * @param {Object} value
  42. * @api private
  43. */
  44. SchemaBoolean.prototype.cast = function (value) {
  45. if (null === value) return value;
  46. if ('0' === value) return false;
  47. if ('true' === value) return true;
  48. if ('false' === value) return false;
  49. return !! value;
  50. }
  51. /*!
  52. * ignore
  53. */
  54. function handleArray (val) {
  55. var self = this;
  56. return val.map(function (m) {
  57. return self.cast(m);
  58. });
  59. }
  60. SchemaBoolean.$conditionalHandlers =
  61. utils.options(SchemaType.prototype.$conditionalHandlers, {
  62. '$in': handleArray
  63. });
  64. /**
  65. * Casts contents for queries.
  66. *
  67. * @param {String} $conditional
  68. * @param {any} val
  69. * @api private
  70. */
  71. SchemaBoolean.prototype.castForQuery = function ($conditional, val) {
  72. var handler;
  73. if (2 === arguments.length) {
  74. handler = SchemaBoolean.$conditionalHandlers[$conditional];
  75. if (handler) {
  76. return handler.call(this, val);
  77. }
  78. return this.cast(val);
  79. }
  80. return this.cast($conditional);
  81. };
  82. /*!
  83. * Module exports.
  84. */
  85. module.exports = SchemaBoolean;