How to Add Calculated Properties to a Model via Mixin in Loopback

loopback-ds-calculated-mixin is a mixin used for the LoopBack framework that adds calculated properties to a model. A calculated property is a property of which the value is set once just before it is persisted to the data source.
The mixin allows you to define a callback that will be run in the before save operation hook to determine and set the value for a given property.
INSTALL
Following steps are involved to install the calculated fields mixin:
Open terminal and go to the root folder of the project.
Run the commands below.
Command for Installing
npm install –save loopback-ds-calculated-mixin
SERVER CONFIG
Add the mixins property to your server/model-config.json:
mixins property
{
“_meta”: {
“sources”: [
“loopback/common/models”,
“loopback/server/models”,
“../common/models”,
“./models”
],
“mixins”: [
“loopback/common/mixins”,
“../node_modules/loopback-ds-calculated-mixin/lib”,
“../common/mixins”
] }
}
CONFIG
To use with your models, add up the mixins property to the definition object of your model config.
The property you want to compute has to be specified in the model. The callback can be a promise too.
Model with calculated mixin
{
“name”: “Item”,
“properties”: {
“name”: “String”,
“description”: “String”,
“status”: “String”,
“readonly”: “boolean”
},
“mixins”: {
“Calculated”: {
“properties”: {
“priceTotal”: {
“recalculateOnUpdate”: true,
“callback”: “calculateTotalPrice”
}
}
}
}
}
On your model you have to define the callback methods.
item.js
‘use strict’;
module.exports = function(Item) {
Item.calculateTotalPrice = function calculateTotalPrice(Item) {
let tp = 0;
let data = Item.__data;
if (data.quantity === null || data.quantity === undefined ||
data.price === null || data.price === undefined) {
return 0;
}
tp = data.quantity * data.price;
return tp;
};
}