如何为具有参数和关系的方法编写远程挂钩

How to write remote hook for a method with parameter and relation

我完成了远程挂钩 documentation,我可以成功地为没有额外参数的方法创建远程挂钩,比如 login, 即:

customer.afterRemote('login', function(ctx, modelInstance, next) {
      if (ctx.result) {
          ...
          next();
      }
      else{
          next();
      }
    });

现在,如何为方法编写远程挂钩说:

GET /customers/{id}

POST /customers/{id}

或 在发布相关对象时

POST /customers/{id}/contacts
GET /customers/{id}/contacts

我知道用 POST /customers/{id}/contacts 做以下事情:

customer.beforeRemote('**', function(ctx, user, next) {
  console.log(ctx.methodString, 'was invoked remotely'); // customers.prototype.save was invoked remotely
  next();
});

会return调用的方法的名字像:

customer.prototype.__create__contacts was invoked remotely

但是我还是无法具体hook它,下面的尝试都没有用,hook也没有达到:

customer.beforeRemote('customer.prototype.__create__contacts', function(ctx, user, next)

customer.beforeRemote(customer.prototype.__create__contacts, function(ctx, user, next)

发现了!答案就在here

首先使用 customer.beforeRemote('**', function(ctx, user, next) 捕获方法名称,如我在问题中提到的,然后简单地执行以下操作即可:

customer.beforeRemote('*.__create__assets', function(ctx, user, next) {
      console.log(ctx.methodString, 'was invoked remotely with customers'); // customers.prototype.save was invoked remotely
      next();
    });