Binu Paul
Binu Paul

Reputation: 127

How to override the default loopback model API paths

How can we override the default loopback REST API model end points? For example, I would like to invoke a custom model method named list when the following GET API is invoked.

enter image description here

I am referring to the documentation https://loopback.io/doc/en/lb2/Exposing-models-over-REST.html

1.API endpoint from loopback explorer: http://localhost:3000/api/Assets

2.Model method definition:

Asset.list = function(cb) {
    console.log("called");
}

Asset.remoteMethod('list', {
    http: {path: '/'},
    returns: {type: 'Object', root: true}
});

Upvotes: 0

Views: 2030

Answers (2)

Moshensky Daniil
Moshensky Daniil

Reputation: 21

If you want to use not default path (not used by default methods) you should add new remote method to JSON model config and define method in JS model file:

"methods": {
  "myCustomMethod": {
    "accepts": [
      {
        "arg": "req",
        "type": "object",
        "http": {
          "source": "req"
        }
      }
    ],
    "returns": [
      {
        "type": "Array",
        "root": true
      }
    ],
    "http": {
      "verb": "GET",
      "path": "/myCustomPath"
    }
  }
}

Candidate.myCustomMethod = (req) => {//method code}

If you want to override default loopback path (autogenerated methods) you also should disable default method.

Candidate.disableRemoteMethodByName('find');

So now you can change in JSON config "/myCustomPath" to "/" and your remote method would refer to your function instead of default.

Upvotes: 1

F3L1X79
F3L1X79

Reputation: 2675

Your console.log("called"); should appear in your terminal only, not as a return on your web browser - that's maybe why you aren't seeing it at the moment.

If you want to see something on your web browser, you have to return a value for you callback, like:

module.exports = function (Asset) {

    Asset.list = function(cb) {
        console.log("called");
        cb(false, {'called': true}); // cb(error, returned value(s));
    }

    Asset.remoteMethod('list', {
        http: {verb: 'get'},
        returns: {type: 'Object', root: true}
    });
}

This file should be in your common/model/asset.js


In your server/model-config.json, do not forget to reference your model:

     ...
     "Asset": {
        "dataSource": "yourdatasource", //change this by your datasource name
        "public": true
     }
     ...

Upvotes: 0

Related Questions