Loopback-next: How to add a sequence/action in loopback 4 on model

Created on 27 Feb 2019  路  4Comments  路  Source: strongloop/loopback-next

In LB 3 there was "observer" for "before save" on a Model.

In LB 4 this should be replaced by sequence/actions.

I am looking for an example/documentation how to do it on a model.

question

All 4 comments

Hi @danysz , the sequence/actions are probably for the request/response flow and not tight to any repository or database operation. In order to make hooks/triggers/onUpdateExit business logic to work, I use the repository itself.

For example, having the following code in a repository, you can see perfectly how we can attach code before and after the creation of a record, so you can manipulate the record before and after. You can inject other repositories in case you want to make updates to any other model (tables). Notice that no code was changed in the controller, only in the repository.

async create(record: MyModel): Promise<MyModel> {
    console.log('this is before saving ');
    record = await super.create(record);
    console.log('this is after saving ');
    return record;
  }

For instance, let's say that you want to deduct the balance of an invoice based upon a payment, we could inject the invoice repository in the payment repository and have the following: (warning: pseudo code, myInvoice is a private variable from InvoiceModel);

async create(payment: PaymentModel): Promise<PaymentModel> {
   try {
             payment = await super.create(payment);  
             myInvoice = await this.myInjectedInvoiceRepository.findById(payment.invoiceID);
             myInvoice.balance = myInvoice.balance - payment.amount;
             myInvoice = await this.myInjectedInvoiceRepository.updateById(payment.invoiceID, myInvoice);
     } catch(err) {
        throw err;
    }
     // if no error, then return the payment record as usual
     return payment;
  }

@danysz, does @marioestradarosa's above comment solve your question? Thanks.

@danysz Have you checked out https://loopback.io/doc/en/lb4/Interceptors.html?

There is a PR https://github.com/strongloop/loopback-next/pull/2927 to make actions more pluggable.

Closing as resolved.

Was this page helpful?
0 / 5 - 0 ratings