Exposing get fields

It would be great to be able to deliver calculations as fields, as though they were attributes.

In the order-item.entity file, we still need to add the get field that calculates the subTotal of an item.

get subTotal() {
  return this.quantity * this.price;
}

And in order.entity, calculate the total by adding the subTotals of its items.

get total() {
  return this.items?.reduce((acc, current) => acc + current.subTotal, 0);
}

Due to the optional chaining operator (?), this calculation only occurs if the items field is present. This is a good safety measure as items is a relation and may not be present.

It would be even better if these get fields were automatically included in their respective entities when they are fetched, like if they were attributes. To achieve this, we first need to enable the ClassSerializerInterceptor globally. We can do this in the providers array of the CommonModule.

{
  provide: APP_INTERCEPTOR,
  useClass: ClassSerializerInterceptor,
},

After that, we just need to add on top of both these fields the @Expose() decorator, and we're done.

Commit - Using serialization to return get fields

Last updated