Do you have any plan to support computed fields in models?
You can implement computed fields using $parseDatabaseJson and $formatDatabaseJson methods like this:
class Person extends Model {
$parseDatabaseJson(row) {
let obj = super.$parseDatabaseJson(row);
obj.fullName = obj.firstName + ' ' + obj.lastName;
}
$formatDatabaseJson(obj) {
// Delete our computed property so that it is not inserted into db.
delete obj.fullName;
return super.$formatDatabaseJson(obj);
}
}
Or is there something I'm missing that this doesn't solve? I'm not a fan of a adding something like:
class Person extends Model {
static get virtuals() {
return {
fullName(model) {
return model.firstName + model.lastName;
}
};
}
}
That was basically the same amount of code and adds another feature to maintain.
Using ES6 you can also solve this using getters, which is a better solution as it keeps the computed properties up-to-date:
class Person extends Model {
get fullName() {
return this.firstName + ' ' + this.lastName;
}
$formatJson(obj) {
obj = super.$formatJson(obj);
// Getter properties are not enumerable, so we need to add them
// to the output object explicitly.
obj.fullName = this.fullName;
return obj;
}
}
You can do this with ES5 also using Object.defineProperty.
The only downside here is that you need to add code in two places instead of one, if we had a direct support for virtual fields.
Great! I'm using es6 so getters seems to be the way to go. Thanks for the help (and for such a cool ORM ;))
@afm-sayem You're welcome! I forgot to return the object from the $formatJson method in the above example if you didn't already notice this. I updated the example.
What is the ES5 equivalent for this? I can't yet move to ES6.
@retorquere Objection now has a real support for virtual attributes. Check out the documentation
http://vincit.github.io/objection.js/#virtualattributes
Updated link to virtual attributes documentation: https://vincit.github.io/objection.js/api/model/static-properties.html#static-virtualattributes
@retorquere Objection now has a real support for virtual attributes. Check out the documentation
http://vincit.github.io/objection.js/#virtualattributes
Is there no way to make the returned json object have a value that is based on existing fields?
For example, the jsonSchema() {
properties: {
full_name = this.firstName + ' ' + this.lastName
}
}
My turn to update the URL
http://vincit.github.io/objection.js/api/model/static-properties.html#static-virtualattributes
Most helpful comment
@retorquere Objection now has a real support for virtual attributes. Check out the documentation
http://vincit.github.io/objection.js/#virtualattributes