Skip to content

Commit

Permalink
feat(entity computed property): define function properties, updating …
Browse files Browse the repository at this point in the history
…them when properties are set

feature herbsjs#68
  • Loading branch information
Your Name committed Dec 28, 2022
1 parent ae6be8e commit c321088
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
31 changes: 29 additions & 2 deletions src/baseEntity.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,36 @@ class BaseEntity {
constructor() {
for (const [name, definition] of Object.entries(this.meta.schema)) {
// ignore functions
if (checker.isFunction(definition)) continue
if (checker.isFunction(definition)) continue;

Object.defineProperty(this, name, {
set: function(value) {
this[`_${name}`] = value;
this.updateFunctionProperties();
},
get: function() {
return this[`_${name}`];
},
});

this[name] = definition.defaultValue;
}
}

this[name] = definition.defaultValue
updateFunctionProperties() {
for (const [field, definition] of Object.entries(this.meta.schema)) {
if (definition.options && checker.isFunction(definition.options.value)) {
const functionValue = definition.options.value;

Object.defineProperty(this, field, {
get: function() {
return functionValue(this);
},
set: function() {
throw new Error('Cannot set a property of function type');
},
});
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion test/field/scalarTypes/string.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ describe('A field', () => {
})
//when
const instance = new AnEntity()
//then
//then
assert.deepStrictEqual(instance['field1'], "Of Life")
})

Expand Down

0 comments on commit c321088

Please sign in to comment.