Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add applyDefaultOnWrites property [3.x] #1770

Merged
merged 1 commit into from
Aug 19, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
feat: add applyDefaultOnWrites property
Adds the ability to ignore writing default values to the database.
Hage Yaapa committed Aug 19, 2019
commit 020d3179aa5aec8f07756ae9309d1ef65e2714b9
15 changes: 15 additions & 0 deletions lib/dao.js
Original file line number Diff line number Diff line change
@@ -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];
hacksparrow marked this conversation as resolved.
Show resolved Hide resolved
}
}

return obj;
}

function stillConnecting(dataSource, obj, args) {
if (typeof args[args.length - 1] === 'function') {
return dataSource.ready(obj, args);
25 changes: 25 additions & 0 deletions test/defaults.test.js
Original file line number Diff line number Diff line change
@@ -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});
hacksparrow marked this conversation as resolved.
Show resolved Hide resolved

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');
});
});
});