feat: added persistDefaultValues (#1815)

Ignores value if it matches default value.
This commit is contained in:
Hage Yaapa 2019-12-17 21:23:29 +05:30 committed by Diana Lau
parent db2a59ef7d
commit 9979efd040
2 changed files with 55 additions and 0 deletions

View File

@ -299,6 +299,10 @@ ModelBaseClass.prototype._initProperties = function(data, options) {
}
}
if (ignoresMatchedDefault(properties[p]) && properties[p].default === propVal) {
delete self.__data[p];
}
// Set default value using a named function
if (applyDefaultValues && propVal === undefined) {
const defn = properties[p].defaultFn;
@ -362,6 +366,13 @@ ModelBaseClass.prototype._initProperties = function(data, options) {
this.trigger('initialize');
};
// Implementation of persistDefaultValues property
function ignoresMatchedDefault(property) {
if (property && property.persistDefaultValues === false) {
return true;
}
}
// Helper function for determing the applyDefaultOnWrites value of a property
function appliesDefaultsOnWrites(property) {
if (property && ('applyDefaultOnWrites' in property)) {

View File

@ -131,4 +131,48 @@ describe('defaults', function() {
found.qualities.length.should.equal(1);
});
});
context('persistDefaultValues', function() {
it('removes property if value matches default', async () => {
const Apple = db.define('Apple', {
color: {type: String, default: 'red', persistDefaultValues: false},
taste: {type: String, default: 'sweet'},
}, {applyDefaultsOnReads: false});
const apple = await Apple.create({color: 'red', taste: 'sweet'});
const found = await Apple.findById(apple.id);
should(found.color).be.undefined();
found.taste.should.equal('sweet');
});
it('removes property if value matches default in an object', async () => {
const Apple = db.define('Apple', {
name: {type: String},
qualities: {
color: {type: String, default: 'red', persistDefaultValues: false},
taste: {type: String, default: 'sweet'},
},
}, {applyDefaultsOnReads: false});
const apple = await Apple.create({name: 'Honeycrisp', qualities: {taste: 'sweet'}});
const found = await Apple.findById(apple.id);
should(found.qualities.color).be.undefined();
found.qualities.taste.should.equal('sweet');
});
it('removes property if value matches default in an array', async () => {
const Apple = db.define('Apple', {
name: {type: String},
qualities: [
{color: {type: String, default: 'red', persistDefaultValues: false}},
{taste: {type: String, default: 'sweet'}},
],
}, {applyDefaultsOnReads: false});
const apple = await Apple.create({name: 'Honeycrisp', qualities: [{taste: 'sweet'}]});
const found = await Apple.findById(apple.id);
should(found.qualities[0].color).be.undefined();
found.qualities.length.should.equal(1);
});
});
});