feat: add applyDefaultOnWrites property

Adds the ability to ignore writing default values to the database.
This commit is contained in:
Hage Yaapa 2019-08-19 17:11:27 +05:30
parent 814c55c7cd
commit 464610ef0a
2 changed files with 40 additions and 0 deletions

View File

@ -431,6 +431,8 @@ DataAccessObject.create = function(data, options, cb) {
});
}
val = applyDefaultsOnWrites(val, Model.definition);
context = {
Model: Model,
data: val,
@ -452,6 +454,19 @@ DataAccessObject.create = function(data, options, cb) {
return cb.promise;
};
// Implementation of applyDefaultOnWrites property
function applyDefaultsOnWrites(obj, modelDefinition) {
for (const key in modelDefinition.properties) {
const prop = modelDefinition.properties[key];
if ('applyDefaultOnWrites' in prop && !prop.applyDefaultOnWrites &&
prop.default !== undefined && prop.default === obj[key]) {
delete obj[key];
}
}
return obj;
}
function stillConnecting(dataSource, obj, args) {
if (typeof args[args.length - 1] === 'function') {
return dataSource.ready(obj, args);

View File

@ -75,4 +75,29 @@ describe('defaults', function() {
});
});
});
context('applyDefaultOnWrites', function() {
it('does not affect default behavior when not set', async () => {
const Apple = db.define('Apple', {
color: {type: String, default: 'red'},
taste: {type: String, default: 'sweet'},
}, {applyDefaultsOnReads: false});
const apple = await Apple.create();
apple.color.should.equal('red');
apple.taste.should.equal('sweet');
});
it('removes the property when set to `false`', async () => {
const Apple = db.define('Apple', {
color: {type: String, default: 'red', applyDefaultOnWrites: 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');
});
});
});