0

Requirement is that for each get request I need to send all the objects in that table. For e.g. I make a request to get all clients (maybe with some filters) with certain limit for pagination purposes and in the response I want the result as array of all client objects and the count of total clients in the DB.

That means I not only need to intercept the find method for each controller or model (wherever its possible) as well as need to modify the response as well.

Current response is:

[
  {
    "firstName": "Bhupesh",
    "lastName": "Gupta"
  }
]

Required response is:

{
  "count": 5,
  "data": [
      {
        "firstName": "Bhupesh",
        "lastName": "Gupta"
      }
    ]
}
Madaky
  • 389
  • 1
  • 9
user3170450
  • 375
  • 3
  • 20
  • Hooks implementation is in pending state https://github.com/strongloop/loopback-next/issues/1919 for loopback 4 – user3170450 Jul 11 '19 at 12:17

2 Answers2

1

You can use operation hooks offered by loopback, check the example mentioned below,

MyModel.observe('access', async function(ctx) {
  var count = // some logic here;
  ctx.result = {
     data: ctx.result,
     count: count
  };

  next();
});

access in operation hooks is used as callback for every GET operation perform in respective datasource.

For more info of operation hooks please check,

https://loopback.io/doc/en/lb2/Operation-hooks.html

https://github.com/strongloop/loopback/issues/624#issuecomment-58549692

Arsal Imam
  • 2,882
  • 2
  • 24
  • 35
0

You can find here: https://strongloop.com/strongblog/loopback4-interceptors-part2/

 import {intercept, Interceptor} from '@loopback/core';
 const validateOrder: Interceptor = async (invocationCtx, next) => {
     console.log('log: before-', invocationCtx.methodName);
     const order: Order = new Order();
     if (invocationCtx.methodName == 'create')
         Object.assign(order, invocationCtx.args[0]);
     else if (invocationCtx.methodName == 'updateById')
         Object.assign(order, invocationCtx.args[1]);

     if (order.orderNum.length !== 6) {
         throw new HttpErrors.InternalServerError('Invalid order number');
     }

     const result = await next();
     return result;
 };


@intercept(validateOrder)
export class OrderController {
    //...
}
Tan Nguyen
  • 947
  • 7
  • 8