5

I'm using strongloop's loopbackjs at work to implement an API.

For a model Cat I have defined a remote method, lets call it meow.

So i can do:

GET /cats/{:id}/meow

The Cat model belongsTo the User model.

Now I would like to be able to do something like this:

GET /users/{:id}/cats/{:id}/meow

Does anyone know how to do this?

I already tried nestRemoting, which only works for nested 'blueprint' methods.

Maxime Rouiller
  • 13,614
  • 9
  • 57
  • 107

3 Answers3

3

You can define a remote method in the User Model and then use it to call the meow method of CatModel

UserModel.someRemoteMethod = function(id1,id2,cb){
     CatModel.meow(id2,cb);
 }


  UserModel.remoteMethod(
    'someRemoteMethod',
    {
      accepts: [
        {arg: 'id1', type: 'number', required: true},
        {arg: 'id2', type: 'number', required: true}
      ],
      http: {path: '/:id1/cats/:id2/meow', verb: 'get'}
    }
  );
SteveR
  • 2,496
  • 1
  • 24
  • 23
Harshil Lodhi
  • 7,274
  • 1
  • 33
  • 42
0

Use nestRemoting('relationName'). It's not well documented, but for your model you can use:

User.on('attached', function() {
   User.nestRemoting('catRelation');
}

Put this in your user.js file and you should get the endpoints you're after.

sidewaiise
  • 1,445
  • 3
  • 16
  • 27
0

I got a solution i need to share with all of you

nestRemoting function take an options json object which contain an attribute called filterMethod this method filter the model function to get only the defaults methods so i passed this attribute callback function with customization in the ( else if ) to check my remote method ( DoWhat ) and return it

server.models.Client.nestRemoting('units', {filterMethod: function(method, relation) {
        let regExp = /^__([^_]+)__([^_]+)$/;
        let matches = method.name.match(regExp);
        if (matches) {
            return '__' + matches[1] + '__' + relation.name + '__' + matches[2];
        } else if (method.name === 'DoWhat') {
            return method.name;
        }
    }});

I hope this solution help you