Skip to content

Commit

Permalink
fix(boolean): expose convertToTrue and convertToFalse for custom …
Browse files Browse the repository at this point in the history
…boolean casting

Fix #6758
  • Loading branch information
vkarpov15 committed Jul 23, 2018
1 parent 0ff9359 commit a37fd2f
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 6 deletions.
11 changes: 5 additions & 6 deletions lib/cast/boolean.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@

const CastError = require('../error/cast');

const convertToTrue = [true, 'true', 1, '1', 'yes'];
const convertToFalse = [false, 'false', 0, '0', 'no'];

/*!
* Given a value, cast it to a boolean, or throw a `CastError` if the value
* cannot be casted. `null` and `undefined` are considered valid.
Expand All @@ -21,12 +18,14 @@ module.exports = function castBoolean(value, path) {
return value;
}

// strict mode (throws if value is not a boolean, instead of converting)
if (convertToTrue.indexOf(value) !== -1) {
if (module.exports.convertToTrue.has(value)) {
return true;
}
if (convertToFalse.indexOf(value) !== -1) {
if (module.exports.convertToFalse.has(value)) {
return false;
}
throw new CastError('boolean', value, path);
};

module.exports.convertToTrue = new Set([true, 'true', 1, '1', 'yes']);
module.exports.convertToFalse = new Set([false, 'false', 0, '0', 'no']);
40 changes: 40 additions & 0 deletions lib/schema/boolean.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,46 @@ SchemaBoolean.prototype.checkRequired = function(value) {
return value === true || value === false;
};

/**
* Configure which values get casted to `true`.
*
* ####Example:
*
* const M = mongoose.model('Test', new Schema({ b: Boolean }));
* new M({ b: 'affirmative' }).b; // undefined
* mongoose.Schema.Boolean.convertToTrue.add('affirmative');
* new M({ b: 'affirmative' }).b; // true
*
* @property convertToTrue
* @type Set
* @api public
*/

Object.defineProperty(SchemaBoolean, 'convertToTrue', {
get: () => castBoolean.convertToTrue,
set: v => { castBoolean.convertToTrue = v; }
});

/**
* Configure which values get casted to `false`.
*
* ####Example:
*
* const M = mongoose.model('Test', new Schema({ b: Boolean }));
* new M({ b: 'nay' }).b; // undefined
* mongoose.Schema.Types.Boolean.convertToFalse.add('nay');
* new M({ b: 'nay' }).b; // false
*
* @property convertToFalse
* @type Set
* @api public
*/

Object.defineProperty(SchemaBoolean, 'convertToFalse', {
get: () => castBoolean.convertToFalse,
set: v => { castBoolean.convertToFalse = v; }
});

/**
* Casts to boolean
*
Expand Down

0 comments on commit a37fd2f

Please sign in to comment.