All files query-with-current-user.js

88.89% Statements 16/18
85.71% Branches 12/14
100% Functions 1/1
88.89% Lines 16/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 391x 1x   1x           11x 11x 11x 1x     10x 2x 1x     1x     8x   7x   7x       7x 7x            
import get from 'lodash.get';
import set from 'lodash.set';
 
const defaults = {
  idField: '_id',
  as: 'userId',
  expandPaths: true
};
 
export default function (options = {}) {
  return function (hook) {
    if (hook.type !== 'before') {
      throw new Error(`The 'queryWithCurrentUser' hook should only be used as a 'before' hook.`);
    }
 
    if (!hook.params.user) {
      if (!hook.params.provider) {
        return hook;
      }
 
      throw new Error('There is no current user to associate.');
    }
 
    options = Object.assign({}, defaults, hook.app.get('authentication'), options);
 
    const id = get(hook.params.user, options.idField);
 
    Iif (id === undefined) {
      throw new Error(`Current user is missing '${options.idField}' field.`);
    }
 
    Eif (options.expandPaths) {
      set(hook.params, `query.${options.as}`, id);
    } else {
      hook.params.query[options.as] = id;
    }
  };
}