diff --git a/lib/index.js b/lib/index.js index cd5219e..f6521f4 100644 --- a/lib/index.js +++ b/lib/index.js @@ -6,6 +6,8 @@ var Sequelize = require('sequelize') init = function(target) { if (target.prototype instanceof Sequelize.Model) { var $get = target.prototype.get; + var $set = target.prototype.set; + var $_initValues = target.prototype._initValues; Object.keys(target.rawAttributes).forEach(function (attr) { if (target.rawAttributes[attr].roles !== undefined) { @@ -72,6 +74,39 @@ init = function(target) { return response; }; + + target.prototype.set = function(key, value, options) { + options = options || {}; + + if (typeof key === 'object' && key !== null) { + return $set.call(this, key, value, options); + } + else { + var attr = target.rawAttributes[key]; + if (options.raw || !attr || !attr.roles || attr.roles && attr.roles[options.role] && attr.roles[options.role].set) { + return $set.call(this, key, value, options); + } + + return target; + } + }; + + // Extend _initValues to ensure the default values are set. + target.prototype._initValues = function(values, options) { + var filtered = {}; + values = values || {}; + options = options || {}; + + Object.keys(values).forEach(function (key) { + var attr = target.rawAttributes[key]; + var val = values[key]; + if (options.raw || !attr || !attr.roles || attr.roles && attr.roles[options.role] && attr.roles[options.role].set) { + filtered[key] = val; + } + }); + + return $_initValues.call(this, filtered, options); + }; } else { target.afterDefine(function (Model) { init(Model); diff --git a/test/get.test.js b/test/get.test.js index 80e2254..9d83694 100644 --- a/test/get.test.js +++ b/test/get.test.js @@ -58,7 +58,7 @@ describe('get', function () { attr1: Math.random().toString(), attr2: Math.random().toString(), attr3: Math.random().toString() - }); + }, { raw: true }); values = instance.get(); @@ -73,7 +73,7 @@ describe('get', function () { expect(values.attr3).not.to.be.ok(); values = instance.get({raw: true}); - + expect(values.attr1).to.be.ok(); expect(values.attr2).to.be.ok(); expect(values.attr3).to.be.ok(); @@ -121,7 +121,7 @@ describe('get', function () { attr1: Math.random().toString(), attr2: Math.random().toString(), attr3: Math.random().toString() - }); + }, { raw: true }); expect(instance.get('attr1', {role: 'rolea'})).to.be.ok(); expect(instance.get('attr1', {role: 'roleb'})).not.to.be.ok(); @@ -188,6 +188,7 @@ describe('get', function () { name: Math.random().toString() } }, { + raw: true, role: 'system', include: [Company] }); @@ -241,4 +242,4 @@ describe('get', function () { expect(account.get('active', {role: 'admin'})).to.equal(true); }); -}); \ No newline at end of file +});