feat: add applyDefaultOnWrites property

Adds the ability to ignore writing default values to the database.
This commit is contained in:
Hage Yaapa 2019-08-09 19:43:35 +05:30
parent eac0d6af87
commit 020d3179aa
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

@ -76,4 +76,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');
});
});
});