Home » Nodejs » How Can I Create a Loopback Remote Method with a Model Schema?

How Can I Create a Loopback Remote Method with a Model Schema?

Posted by: admin November 30, 2017 Leave a comment

Questions:

I’m currently building a loopback application, which only has a single model named Phone. Here’s my common/models/phone.js code:

module.exports = function(Phone) {

  // Return a random phone's data.
  Phone.random = function(callback) {
    return callback(null, {
      id: '12345',
      number: '+18182179222',
      name: 'Randall Degges'
    });
  };

  Phone.remoteMethod('random', {
    description: 'Return a random phone.',
    accepts: [],
    returns: [
      //{ type: 'object', root: true, description: 'return value' },
      { arg: 'id', type: 'string', description: 'phone id', required: true, root: true },
      { arg: 'number', type: 'string', description: 'phone number', required: true, root: true },
      { arg: 'name', type: 'string', description: 'phone name', required: false, root: true }
    ],
    http: {
      verb: 'get', path: '/random',
    }
  });

};

When I pull up my API explorer on port 3000, and view my newly created random API call, I see the following:

Random API Call in Loopback Explorer

As you can see above, my “Model Schema” is empty. Booo!

What I’d like to accomplish is something similar to the built-in API methods, which look something like this:

Working API Call in Loopback Explorer

As you can see above, the “Model Schema” shows what the actual output of the API call will look like.

I’m trying to figure out how to accomplish this with my remote endpoint, but so far have had no luck.

Any suggestions are welcome.

BONUS POINTS: Is there a way to simply tell Loopback that my return value is just an already-defined model? In my case all I’m doing is returning an existing Phone model, so it would be nice to just let Loopback know that somehow and have it auto-generate the documentation accordingly.

Thank you!

Answers:

Try running your app with de following command:

DEBUG=loopback:explorer:routeHelpers node .

you will be able to see what returns options use de built in API methods

You must use a model structure defined in the common/models directory in the returns parameter like

returns: [{arg:"data",type:"Mymodels",root:true}]

Questions:
Answers:

For your bonus points:

When you call the remoteMethod() you have to specify the model of the schema you want to return:

returns: { arg: 'data', type: 'Phone', root: true}

Extra: if the wanted schema is of another model, you have to require it as well, in order to avoid ‘undefined’ errors:

module.exports = function(Model1) {
     var app = require('../../server/server');

     Model1.someMethod = function(args, cb) {
         var Model2 = app.models.Model2;
             [...] 
         }