Skip to content

Commit

Permalink
feat: add applyDefaultOnWrites property
Browse files Browse the repository at this point in the history
Adds the ability to ignore writing default values to the database.
  • Loading branch information
Hage Yaapa committed Aug 16, 2019
1 parent 507621c commit fe99fd7
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
15 changes: 15 additions & 0 deletions lib/dao.js
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,8 @@ DataAccessObject.create = function(data, options, cb) {
});
}

val = applyDefaultsOnWrites(val, Model.definition);

context = {
Model: Model,
data: val,
Expand All @@ -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);
Expand Down
25 changes: 25 additions & 0 deletions test/defaults.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
(found.color === undefined).should.be.ok();
found.taste.should.equal('sweet');
});
});
});

0 comments on commit fe99fd7

Please sign in to comment.