Yevhenii Bahmutskyi
Yevhenii Bahmutskyi

Reputation: 1661

Loopback. How to get all roles for one user?

I'm creating a Loopback application and have created a custom user model, based on built-in User model.

{
  "name": "user",
  "base": "User",
  "idInjection": true,
  "properties": {
    "test": {
      "type": "string",
      "required": false
    }
  },
  "validations": [],
  "acls": [],
  "methods": []
}

Then in boot script I'm creating (if not exists) new user, new role and a roleMapping.

User.create(
{ username: 'admin', email: '[email protected]', password: 'pass' }
, function (err, users) {
    if (err) throw err;

    console.log('Created user:', users);

    //create the admin role
    Role.create({
        name: 'admin'
    }, function (err, role) {
        if (err) throw err;

        //make user an admin
        role.principals.create({
            principalType: RoleMapping.USER,
            principalId: users.id
        }, function (err, principal) {
            if (err) throw err;
            console.log(principal);
        });
    });
});

Then in custom remote method I'm trying to get all roles for User, using user's id. Loopbacks' documentation on this topic says that

Once you define a “hasMany” relation, LoopBack adds a method with the relation name to the declaring model class’s prototype automatically. For example: Customer.prototype.orders(...).

And gives this example:

customer.orders([filter], function(err, orders) { ... });

But when I am trying to use User.roles() method, (const User = app.models.user;) I get the next error:

TypeError: User.roles is not a function

But when I'm making a remote request http://localhost:9000/api/users/5aab95a03e96b62718940bc4/roles, I get the desired roleMappings array.

So, i would appreciate if someone could help get this data using js. I know I can probably just query the RoleMappings model, but I've wanted to do it the documentation-way.

Upvotes: 1

Views: 1597

Answers (2)

Leo
Leo

Reputation: 844

This is an old question, but I faced the same issue and was able to solve it by having the relation Antonio Trapani suggested and accessing the roles like this:

const userInstance = await User.findById(userId);
const roles = await userInstance.roles.find();

Roles is not a function, it is an object. By the way this is using loopback 3.

Upvotes: 0

Antonio Trapani
Antonio Trapani

Reputation: 811

Loopback documentation suggests to extend the built-in user model to add more properties and functionalities.

A good practice is creating a model Member that extends the built-in model User. In the new model declare the following relationship:

"relations": { "roles": { "type": "hasMany", "model": "RoleMapping", "foreignKey": "principalId" } }

Now, you can get all the user roles:

user.roles(function (err, roles) {
  // roles is an array of RoleMapping objects
})

where user is an instance of Member.

Upvotes: 2

Related Questions