feat: Getter e setter dinamici sugli attributi del Model

This commit is contained in:
Maicol Battistini 2021-12-18 14:54:34 +01:00
parent 13a320a6ac
commit 5a1e7a85e4
No known key found for this signature in database
GPG Key ID: 4FDB0F87CDB1D34A
1 changed files with 27 additions and 0 deletions

View File

@ -8,6 +8,33 @@ import {snakeCase} from 'lodash-es';
* @property {number} id
*/
export default class Model extends BaseModel {
constructor() {
super();
// Return a proxy of this object to allow dynamic attributes getters and setters
return new Proxy(this, {
get(target: this, property, receiver) {
const snakeCasedProperty = snakeCase(property);
if (snakeCasedProperty in target.getAttributes()) {
return target.getAttribute(snakeCasedProperty);
}
return Reflect.get(target, property, receiver);
},
set(target: this, property, value, receiver) {
const snakeCasedProperty = snakeCase(property);
if (snakeCasedProperty in target.getAttributes()) {
target.setAttribute(snakeCasedProperty, value);
return true;
}
return Reflect.set(target, property, value, receiver);
}
});
}
/**
* Just an alias to the get() method.
*