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.

92 lines
1.5 KiB

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