Skip to content

Commit

Permalink
Merge pull request #14124 from Automattic/vkarpov15/gh-14070-2
Browse files Browse the repository at this point in the history
feat(schematype): merge rather than overwrite default schematype validators
  • Loading branch information
vkarpov15 authored Nov 28, 2023
2 parents 29f4da7 + da8462e commit 33e3898
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/schemaType.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@ function SchemaType(path, options, instance) {
const defaultOptionsKeys = Object.keys(defaultOptions);

for (const option of defaultOptionsKeys) {
if (defaultOptions.hasOwnProperty(option) && !Object.prototype.hasOwnProperty.call(options, option)) {
if (option === 'validate') {
this.validate(defaultOptions.validate);
} else if (defaultOptions.hasOwnProperty(option) && !Object.prototype.hasOwnProperty.call(options, option)) {
options[option] = defaultOptions[option];
}
}
Expand Down
31 changes: 31 additions & 0 deletions test/schematype.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,37 @@ describe('schematype', function() {
});
});

it('merges default validators (gh-14070)', function() {
class TestSchemaType extends mongoose.SchemaType {}
TestSchemaType.set('validate', checkIfString);

const schemaType = new TestSchemaType('test-path', {
validate: checkIfLength2
});

assert.equal(schemaType.validators.length, 2);
assert.equal(schemaType.validators[0].validator, checkIfString);
assert.equal(schemaType.validators[1].validator, checkIfLength2);

let err = schemaType.doValidateSync([1, 2]);
assert.ok(err);
assert.equal(err.name, 'ValidatorError');

err = schemaType.doValidateSync('foo');
assert.ok(err);
assert.equal(err.name, 'ValidatorError');

err = schemaType.doValidateSync('ab');
assert.ifError(err);

function checkIfString(v) {
return typeof v === 'string';
}
function checkIfLength2(v) {
return v.length === 2;
}
});

describe('set()', function() {
describe('SchemaType.set()', function() {
it('SchemaType.set, is a function', () => {
Expand Down

0 comments on commit 33e3898

Please sign in to comment.