Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing other models' methods from custom method in Loopback

I'm trying to create a custom method for a User based model in Loopback.

The method calls login and then retrieves user's role and adds it into response so the login request holds token and role info at once.

My problem is that once I have the token information I don't know how to call Role & RoleMapping methods from the one I'm creating...

How can I add those models to the current scope?

How can I access rootScope from this method?

This is how I've made it:

module.exports = function(TiUser) {

  TiUser.auth = function(credentials, include, fn) {
    var self = this;

    self.login(credentials, include, function(err, token) {

      var role = // Here I would retrieve Role related info

      authInfo = {
        token: token,
        role: role
      };

      fn(err, authInfo);
    });
  };
  TiUser.remoteMethod(
    'auth',
    {
      description: 'Login method with Role data information embedded in return',
      accepts: [
        {arg: 'credentials', type: 'object', required: true, http: {source: 'body'}},
        {arg: 'include', type: ['string'], http: {source: 'query' },
          description: 'Related objects to include in the response. ' +
          'See the description of return value for more details.'}
      ],
      returns: {
        arg: 'accessToken', type: 'object', root: true,
        description: 'User Model'
      },
      http: {verb: 'post'}
    }
  );
};
like image 331
F.D.F. Avatar asked Mar 15 '23 18:03

F.D.F.


1 Answers

You can get back to app from your models like so TiUser.app

So the way that I call other Model methods is:

TiUser.app.models.Roles.find etc.

like image 104
conradj Avatar answered Mar 23 '23 22:03

conradj