feat: add applyDefaultOnWrites property
Adds the ability to ignore writing default values to the database.
This commit is contained in:
parent
eac0d6af87
commit
020d3179aa
15
lib/dao.js
15
lib/dao.js
|
@ -431,6 +431,8 @@ DataAccessObject.create = function(data, options, cb) {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val = applyDefaultsOnWrites(val, Model.definition);
|
||||||
|
|
||||||
context = {
|
context = {
|
||||||
Model: Model,
|
Model: Model,
|
||||||
data: val,
|
data: val,
|
||||||
|
@ -452,6 +454,19 @@ DataAccessObject.create = function(data, options, cb) {
|
||||||
return cb.promise;
|
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) {
|
function stillConnecting(dataSource, obj, args) {
|
||||||
if (typeof args[args.length - 1] === 'function') {
|
if (typeof args[args.length - 1] === 'function') {
|
||||||
return dataSource.ready(obj, args);
|
return dataSource.ready(obj, args);
|
||||||
|
|
|
@ -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');
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
Loading…
Reference in New Issue