Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 293
rdegges Avatar asked Mar 05 '15 01:03

rdegges


People also ask

What is remote method in LoopBack?

A remote method is a 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. Note: The easiest way to define a remote method is by using the command-line remote method generator.

What is model in LoopBack?

A LoopBack model is a JavaScript object with both Node and REST APIs that represents data in backend systems such as databases. Models are connected to backend systems via data sources. You use the model APIs to interact with the data source to which it is attached.


1 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}]

like image 74
Adolfo Avatar answered Oct 04 '22 21:10

Adolfo