-
Notifications
You must be signed in to change notification settings - Fork 56
Generated Properties
Sometimes a property needs to be generated on the fly (for example password salts). To do so we need to pay attention to a few things:
- Getters and Setters.
- Properly setting properties.
- Instanciation before Validation.
For this example we will be working with a User
resource.
Generally the best place to put getters and setters in on the prototype. Since we want to be able to manually set properties on creation we will use both a getter and a setter. The getter will generate a new value, and the setter will set the value. After generating a value we may not wish to regenate it afterward. A good solution to prevent regeneration is to redefine the property after generation using Object.defineProperty
and a simple value descriptor.
After we have redefined our property we will also need to get resourceful to recognize it (since it is a non-standard property). For this use resource.writeProperty(key, value)
.
When validation occurs we will need to ensure that the property is generated. The easiest way to do this is to just grab the property from the object and have the getter and setter do the work for us. After that is done we can use the default Resource validation to ensure compatibility.
var saltChars = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
Object.defineProperty(User.prototype, 'salt', {
get: function getSalt() {
function getChar() {
return saltChars[Math.floor(Math.random() * saltChars.length)];
};
var salt = "";
for(var i = 0; i < 20; i++) {
salt += getChar();
}
this.salt = salt;
return this.salt;
},
set: function setSalt(value) {
Object.defineProperty(this, 'salt', {value: value, configurable: false, enumerable: true});
this.writeProperty('salt', value);
},
configurable: true,
enumerable: true
});