Create a Remote Method in LoopBack

By default loopback create all CRUD API of Models. But sometime we have special requirements that not full fill by auto generated methods(Rest APIs). In this situation  we need to create custom remote methods in models.

A remote method is a static method of a model, exposed over a custom REST endpoint.Use a remote method to perform operations not provided by LoopBack’s standard model REST API.

How to define a remote method :

Step 1 :-
Edit the Model definition JSON file in /common/models directory; for example, to attach a remote method to the Page model, edit /common/models/page.js. If you created the model with the Model generator, then this file will already exist.

In this example I am going to create a Remote Method in page.js File.

Step 2:-

Define a static method that will handle the request.


module.exports = function(Page) {

Page.remoteMethod('customRemoteMethod', {
     http: {path: '/customRemoteMethod', verb: 'get'},
     accepts: [
     {arg: 'slug', type: 'string', http: {source: 'query'}, required: true}
     ],
     returns: {root: true, type: 'object'},
     description: 'Custom Remote Method'
     });
}

Let discuss on above code, here I create “customRemoteMethod” custom remote method which is handle GET request. This request accept argument “slug” in query type and it is required.

And “customRemoteMethod” return response in object.

Step 3:-

Call remoteMethod(), to register the method, calling it with two parameters:


module.exports = function(Page) {

    Page.customRemoteMethod = function (slug, cb) {
        //code goes here
        cb(null, {'response': 'ok'});
    };
}

Full Code Example:-

module.exports = function(Page) {

//Call remote Method
  Page.customRemoteMethod = function (slug, cb) {

    //code goes here

    cb(null, {'response': 'ok'});

  };

//Create remote Method
  Page.remoteMethod('customRemoteMethod', {
    http: {path: '/customRemoteMethod', verb: 'get'},
    accepts: [
      {arg: 'slug', type: 'string', http: {source: 'query'}, required: true}
    ],
    returns: {root: true, type: 'object'},
    description: 'Generate Page slug'
  });

}

Now this custom Remote method is show in Rest API Explorer.

Leave a Reply

Your email address will not be published. Required fields are marked *