All files populate-user.js

94.44% Statements 17/18
78.57% Branches 11/14
100% Functions 3/3
94.44% Lines 17/18
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46      1x         16x 16x 16x   16x     16x 15x   1x         16x 1x     15x 15x   15x     15x 15x     15x     15x          
/**
 * Populate the current user associated with the JWT
 */
const defaults = {
  userEndpoint: '/users',
  idField: '_id'
};
 
export default function (options = {}) {
  return function (hook) {
    let id;
 
    options = Object.assign({}, defaults, hook.app.get('auth'), options);
 
    // If it's an after hook grab the id from the result
    if (hook.type === 'after') {
      id = hook.result[options.idField];
    // Check to see if we have an id from a decoded JWT
    } else Iif (hook.params.payload) {
      id = hook.params.payload[options.idField];
    }
 
    // If we didn't find an id then just pass through
    if (id === undefined) {
      return Promise.resolve(hook);
    }
 
    return new Promise(function (resolve, reject) {
      hook.app.service(options.userEndpoint).get(id, {}).then(user => {
        // attach the user to the hook for use in other hooks or services
        hook.params.user = user;
 
        // If it's an after hook attach the user to the response
        Eif (hook.result) {
          hook.result.data = Object.assign({}, user = !user.toJSON ? user : user.toJSON());
 
          // remove the id field from the root, it already exists inside the user object
          delete hook.result[options.idField];
        }
 
        return resolve(hook);
      }).catch(reject);
    });
  };
}