Search code examples
loopbackjs

Is there a way to distinguish between custom remote methods and standard remote methods?


In lb v3 is there a way to distinguish between standard remote methods and custom remote methods?

For e.g. I create a remote method as follows:

Customer.order_status = function(orderId, cb) {
// ...
};

Customer.remoteMethod(
// remote method definition
);

Now in suppose a afterRemote() or beforeRemote() call (defined in a mixin for e.g.), is there anyway to figure out if this is a custom remote method call or a standard remote method call (like find, findById, etc)?

TargetModel.beforeRemote('**', function(ctx, next) {
let methodString = ctx.methodString;

}

The method string for a order_status call would be something like Customer.order_status, and, say, if it was defined as a non-static method, it would have been Customer.prototype.order_status. Now, I can test for the truthfullness in the model constructor to determine if it is a valid method.

For e.g.

!!TargetModel[remoteMethodname] // true if it is a valid static method.

However, I don't have the information yet. I don't know if it is a static method defined as a custom remote method.

Further, if we have defined a scope on the model it further complicates things. I cannot distinguish between a scope remote call or a standard remote call based on the above approach.


Solution

  • Hello from the LoopBack team 👋

    We don't distinguish between built-in and user-provided remote methods in LoopBack. However, it is possible to add a flag to remoting metadata for custom methods defined in your project.

    For example:

    Customer.remoteMethod('foo', {
      // your custom flag
      custom: true,
    
      // standard remoting metadata
      accepts: [/*...*/],
      returns: [/*...*/],
      // etc.
    });
    

    Then in your remoting hook, you can access remoting metadata via ctx.method.{field}, for example:

    TargetModel.beforeRemote('**', function(ctx, next) {
      const isCustom = ctx.method.custom;
      // ...
    });