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.

103 lines
1.9 KiB

  1. /*!
  2. * Module dependencies.
  3. */
  4. var utils = require('../utils');
  5. var SchemaType = require('../schematype');
  6. /**
  7. * Boolean SchemaType constructor.
  8. *
  9. * @param {String} path
  10. * @param {Object} options
  11. * @inherits SchemaType
  12. * @api public
  13. */
  14. function SchemaBoolean(path, options) {
  15. SchemaType.call(this, path, options, 'Boolean');
  16. }
  17. /**
  18. * This schema type's name, to defend against minifiers that mangle
  19. * function names.
  20. *
  21. * @api public
  22. */
  23. SchemaBoolean.schemaName = 'Boolean';
  24. /*!
  25. * Inherits from SchemaType.
  26. */
  27. SchemaBoolean.prototype = Object.create(SchemaType.prototype);
  28. SchemaBoolean.prototype.constructor = SchemaBoolean;
  29. /**
  30. * Check if the given value satisfies a required validator. For a boolean
  31. * to satisfy a required validator, it must be strictly equal to true or to
  32. * false.
  33. *
  34. * @param {Any} value
  35. * @return {Boolean}
  36. * @api public
  37. */
  38. SchemaBoolean.prototype.checkRequired = function(value) {
  39. return value === true || value === false;
  40. };
  41. /**
  42. * Casts to boolean
  43. *
  44. * @param {Object} value
  45. * @api private
  46. */
  47. SchemaBoolean.prototype.cast = function(value) {
  48. if (value === null) {
  49. return value;
  50. }
  51. if (value === '0') {
  52. return false;
  53. }
  54. if (value === 'true') {
  55. return true;
  56. }
  57. if (value === 'false') {
  58. return false;
  59. }
  60. return !!value;
  61. };
  62. SchemaBoolean.$conditionalHandlers =
  63. utils.options(SchemaType.prototype.$conditionalHandlers, {});
  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 (arguments.length === 2) {
  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;