Allow override sette and getters

This commit is contained in:
Anatoliy Chakkaev 2011-12-11 15:01:23 +04:00
parent 44267a3ebb
commit 9357c16607
2 changed files with 36 additions and 3 deletions

View File

@ -50,10 +50,18 @@ function AbstractClass(data) {
// Public setters and getters
Object.defineProperty(this, attr, {
get: function () {
if (this.constructor.getter[attr]) {
return this.constructor.getter[attr].call(this);
} else {
return this[_attr];
}
},
set: function (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);
};

View File

@ -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';