thoughts/node_modules/mongoose/lib/schema/boolean.js
node_modules/mongoose/lib/schema/boolean.jsRaw
1/*!
2 * Module dependencies.
3 */
4
5var utils = require('../utils');
6
7var SchemaType = require('../schematype');
8
9/**
10 * Boolean SchemaType constructor.
11 *
12 * @param {String} path
13 * @param {Object} options
14 * @inherits SchemaType
15 * @api public
16 */
17
18function SchemaBoolean(path, options) {
19 SchemaType.call(this, path, options, 'Boolean');
20}
21
22/**
23 * This schema type's name, to defend against minifiers that mangle
24 * function names.
25 *
26 * @api public
27 */
28SchemaBoolean.schemaName = 'Boolean';
29
30/*!
31 * Inherits from SchemaType.
32 */
33SchemaBoolean.prototype = Object.create(SchemaType.prototype);
34SchemaBoolean.prototype.constructor = SchemaBoolean;
35
36/**
37 * Check if the given value satisfies a required validator. For a boolean
38 * to satisfy a required validator, it must be strictly equal to true or to
39 * false.
40 *
41 * @param {Any} value
42 * @return {Boolean}
43 * @api public
44 */
45
46SchemaBoolean.prototype.checkRequired = function(value) {
47 return value === true || value === false;
48};
49
50/**
51 * Casts to boolean
52 *
53 * @param {Object} value
54 * @api private
55 */
56
57SchemaBoolean.prototype.cast = function(value) {
58 if (value === null) {
59 return value;
60 }
61 if (value === '0') {
62 return false;
63 }
64 if (value === 'true') {
65 return true;
66 }
67 if (value === 'false') {
68 return false;
69 }
70 return !!value;
71};
72
73SchemaBoolean.$conditionalHandlers =
74 utils.options(SchemaType.prototype.$conditionalHandlers, {});
75
76/**
77 * Casts contents for queries.
78 *
79 * @param {String} $conditional
80 * @param {any} val
81 * @api private
82 */
83
84SchemaBoolean.prototype.castForQuery = function($conditional, val) {
85 var handler;
86 if (arguments.length === 2) {
87 handler = SchemaBoolean.$conditionalHandlers[$conditional];
88
89 if (handler) {
90 return handler.call(this, val);
91 }
92
93 return this.cast(val);
94 }
95
96 return this.cast($conditional);
97};
98
99/*!
100 * Module exports.
101 */
102
103module.exports = SchemaBoolean;