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