0

要求是对于每个获取请求,我需要发送该表中的所有对象。例如,我请求获取具有一定限制的所有客户端(可能带有一些过滤器)以用于分页目的,并且在响应中我希望将结果作为所有客户端对象的数组和数据库中的总客户端计数。

这意味着我不仅需要拦截每个控制器或模型的 find 方法(尽可能地),还需要修改响应。

目前的回应是:

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

要求的响应是:

{
  "count": 5,
  "data": [
      {
        "firstName": "Bhupesh",
        "lastName": "Gupta"
      }
    ]
}
4

2 回答 2

1

您可以使用环回提供的操作挂钩,请查看下面提到的示例,

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

  next();
});

accessin operation hooks 用作GET在相应数据源中执行的每个操作的回调。

有关操作挂钩的更多信息,请查看,

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

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

于 2019-07-11T11:51:33.670 回答
0

你可以在这里找到: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 {
    //...
}
于 2020-03-24T15:18:04.283 回答