loopback icon indicating copy to clipboard operation
loopback copied to clipboard

problem to handle data from [include] in a query (because is a function)

Open kamilml opened this issue 9 years ago • 12 comments

I am doing this User.login(credentials, 'user', callback) and getting a correct response with the token value, id, ttl, and a user object with all the data of that user instance.

console.log(token) give me this:

{ ttl: 300,
  userId: 5963bbe610dcbb27d812045e,
  created: 2017-07-10T19:33:39.119Z,
  id: '8qxNRBpxwzQFU9qssAHcCy7RSHr0rX1RbEDI4HQ1mfnc3aYTBZSZ9uzT7FVGW2zh',
  user:
   { username: 'Brewmaster 89162',
     avatar: 'img.jpg',
     password: '$2a$10$g5fBCW8z7XrNu.L.JvO01e/DKeODv98eGG1G4ZhcrddNmpGkxX79i',
     email: '[email protected]',
     id: 5963bbe610dcbb27d812045e } 
}

But I want to handle the user object. Making another object with some values from this. But I cant take any value of user. For example token.user.username is undefined.

console.log(token.user) give me this:

{ [Function: bound ]
  getAsync: [Function: bound ],
  update: [Function: bound ],
  destroy: [Function: bound ],
  create: [Function: bound ],
  build: [Function: bound ],
  _targetClass: 'User' }

Help me please :(

kamilml avatar Jul 10 '17 19:07 kamilml

@kamilml I'm curious to see what token.user.getAsync() returns.

Setogit avatar Jul 11 '17 22:07 Setogit

@Setogit token.user.username return a promise, then i do .then() (also .catch()) to catch the response/error but I'm getting null error

kamilml avatar Jul 16 '17 15:07 kamilml

what happened with my question? :(

kamilml avatar Jul 19 '17 23:07 kamilml

If you use callbacks rather than promises, does it work as intended?

SippieCup avatar Jul 31 '17 18:07 SippieCup

@SippieCup can you give me an example of how should be the callback for this please? :)

kamilml avatar Aug 01 '17 01:08 kamilml

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Sep 30 '17 02:09 stale[bot]

I still have not found solutions for this :(

kamilml avatar Sep 30 '17 17:09 kamilml

@Kamilml,

Sorry about not responding earlier, I didn't see your response.

The output from console.log(res) is lying to you for logging purposes. It'll print the data which will be sent back to the client, not the current object.

res.user is actually a constructor and needs to be called in order to get any data from it. Furthermore, and what probably confused you, is that this constructor does not support promises, you have to use a regular callback.

Here's an example of how you should be doing it, please note that Employee is an extension of the User model: The code that is being run:

router.post('/login', function(req, res) {
    Employee.login({
      email: req.body.email,
      password: req.body.password,
      ttl: 300
    }, 'user')
    .then( (response) => {
      console.log("\nthis output is lying to you. this is what will be returned to the client:")
      console.log(response); 
      // This fails because user is not yet truely instantiated.
      console.log(`\nEmail from user before instantiation: ${response.user.email}`)
      // To get data from user, we must call the user property as a function to instantiate it.
      // for some reason response.user() does not support promises, so you have to put it in 
      // a callback
      response.user(function(err, userData) {
        // now you can access data from the included `user` model
        console.log(`Email from user when instantiated: ${userData.email}`);
      });
    })
    .catch( (err) => console.error(err));
  });

basic console logging will print the following:

┌─[sid@dev01] - [~/Source/AnApp] - [Tue Oct 03, 10:25]
└─[$] <git:(master*)> node .
Web server listening at: http://0.0.0.0:3000
Browse your REST API at http://0.0.0.0:3000/explorer

this output is lying to you. this is what will be returned to the client:
{ ttl: 300,
  userId: 77,
  created: 2017-10-03T14:25:13.234Z,
  id: 'sifC6iycomQArgb0jiSPwlh8febQflgLKCmTcvGdvh3mm6swEFENU6ygj9eonbjG',
  user:
   { emailVerified: true,
     password: '*snip*',
     employeename: ''*snip*,
     initials: ''*snip*',
     email: '[email protected]',
     username: 'sid',
     verificationToken: null,
     id: 77 } }

Email from user before instantiation: undefined
Email from user when instantiated: [email protected]

If you want to see what the current object actually is, you have to attach it to a debugger. When you do that you can see what loopback is hiding from basic console.log calls.

debugger

I hope this helps. Let me know if you have any other questions.

SippieCup avatar Oct 03 '17 14:10 SippieCup

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Dec 16 '17 16:12 stale[bot]

This issue has been closed due to continued inactivity. Thank you for your understanding. If you believe this to be in error, please contact one of the code owners, listed in the CODEOWNERS file at the top-level of this repository.

stale[bot] avatar Dec 30 '17 17:12 stale[bot]

@SippieCup I copy/paste your example (modifying Employee / UsersModel) but I got this :(

error

kamilml avatar Dec 30 '17 19:12 kamilml

I'd double check to ensure you did everything correctly, it's probably a race condition.

SippieCup avatar Dec 30 '17 21:12 SippieCup