diff --git a/lib/abstract-class.js b/lib/abstract-class.js index 0d7b2d5c..375ff418 100644 --- a/lib/abstract-class.js +++ b/lib/abstract-class.js @@ -50,10 +50,18 @@ function AbstractClass(data) { // Public setters and getters Object.defineProperty(this, attr, { get: function () { - return this[_attr]; + if (this.constructor.getter[attr]) { + return this.constructor.getter[attr].call(this); + } else { + return this[_attr]; + } }, set: function (value) { - this[_attr] = value; + if (this.constructor.setter[attr]) { + this.constructor.setter[attr].call(this, value); + } else { + this[_attr] = value; + } }, configurable: true, enumerable: true @@ -85,6 +93,9 @@ function AbstractClass(data) { this.trigger("initialize"); }; +AbstractClass.setter = {}; +AbstractClass.getter = {}; + AbstractClass.defineProperty = function (prop, params) { this.schema.defineProperty(this.modelName, prop, params); }; diff --git a/test/common_test.js b/test/common_test.js index 3ebd23ba..84c4fe1f 100644 --- a/test/common_test.js +++ b/test/common_test.js @@ -47,7 +47,8 @@ function testOrm(schema) { bio: Text, approved: Boolean, joinedAt: Date, - age: Number + age: Number, + password: String }); Post = schema.define('Post', { @@ -234,6 +235,27 @@ function testOrm(schema) { }); }); + it('should handle virtual attributes', function (test) { + var salt = 's0m3s3cr3t5a1t'; + + User.setter.password = function (password) { + this._password = calcHash(password, salt); + }; + + function calcHash(pass, salt) { + var crypto = require('crypto'); + var hash = crypto.createHash('sha256'); + hash.update(pass); + hash.update(salt); + return hash.digest('base64'); + } + + var u = new User; + u.password = 's3cr3t'; + test.equal(u.password, calcHash('s3cr3t', salt)); + test.done(); + }); + it('should update single attribute', function (test) { Post.create({title: 'title', content: 'content', published: true}, function (err, post) { post.content = 'New content';