feat: applyDefaultOnWrites in nested properties

Adds support for `applyDefaultOnWrites` in nested properties.
This commit is contained in:
Hage Yaapa 2019-11-26 20:04:57 +05:30 committed by Hage Yaapa
parent d54d769477
commit 89a964e919
2 changed files with 39 additions and 1 deletions

View File

@ -278,7 +278,7 @@ ModelBaseClass.prototype._initProperties = function(data, options) {
const type = properties[p].type;
// Set default values
if (applyDefaultValues && propVal === undefined) {
if (applyDefaultValues && propVal === undefined && appliesDefaultsOnWrites(properties[p])) {
let def = properties[p]['default'];
if (def !== undefined) {
if (typeof def === 'function') {
@ -362,6 +362,14 @@ ModelBaseClass.prototype._initProperties = function(data, options) {
this.trigger('initialize');
};
// Helper function for determing the applyDefaultOnWrites value of a property
function appliesDefaultsOnWrites(property) {
if (property && ('applyDefaultOnWrites' in property)) {
return property.applyDefaultOnWrites;
}
return true;
}
/**
* Define a property on the model.
* @param {String} prop Property name

View File

@ -99,5 +99,35 @@ describe('defaults', function() {
should(found.color).be.undefined();
found.taste.should.equal('sweet');
});
it('removes nested property in an object when set to `false`', async () => {
const Apple = db.define('Apple', {
name: {type: String},
qualities: {
color: {type: String, default: 'red', applyDefaultOnWrites: 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 nested property in an array when set to `false', async () => {
const Apple = db.define('Apple', {
name: {type: String},
qualities: [
{color: {type: String, default: 'red', applyDefaultOnWrites: 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);
});
});
});