Skip to content
This repository was archived by the owner on Aug 29, 2018. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion lib/hooks/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
const hashPassword = require('./hash-password');
const protect = require('./protect');

module.exports = {
hashPassword
hashPassword,
protect
};
24 changes: 24 additions & 0 deletions lib/hooks/protect.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const omit = require('lodash.omit');

module.exports = function (...fields) {
return function protect (hook) {
const result = hook.dispatch || hook.result;
const o = current => omit(current, fields);

if (!result) {
return hook;
}

if (Array.isArray(result)) {
hook.dispatch = result.map(o);
} else if (result.data) {
hook.dispatch = Object.assign({}, result, {
data: result.data.map(o)
});
} else {
hook.dispatch = o(result);
}

return hook;
};
};
89 changes: 89 additions & 0 deletions test/hooks/protect.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/* eslint-disable no-unused-expressions */
const chai = require('chai');

const { protect } = require('../../lib/hooks');
const { expect } = chai;

function testOmit (title, property) {
describe(title, () => {
const fn = protect('password');

it('omits from object', () => {
const data = {
email: 'test@user.com',
password: 'supersecret'
};
const context = {
[property]: data
};
const result = fn(context);

expect(result).to.deep.equal({
[property]: data,
dispatch: { email: 'test@user.com' }
});
});

it('omits from array', () => {
const data = [{
email: 'test1@user.com',
password: 'supersecret'
}, {
email: 'test2@user.com',
password: 'othersecret'
}];
const context = {
[property]: data
};
const result = fn(context);

expect(result).to.deep.equal({
[property]: data,
dispatch: [
{ email: 'test1@user.com' },
{ email: 'test2@user.com' }
]
});
});

it('omits from pagination object', () => {
const data = {
total: 2,
data: [{
email: 'test1@user.com',
password: 'supersecret'
}, {
email: 'test2@user.com',
password: 'othersecret'
}]
};
const context = {
[property]: data
};
const result = fn(context);

expect(result).to.deep.equal({
[property]: data,
dispatch: {
total: 2,
data: [
{ email: 'test1@user.com' },
{ email: 'test2@user.com' }
]
}
});
});
});
}

describe('hooks:protect', () => {
it('does nothing when called with no result', () => {
const fn = protect();
const original = {};

expect(fn(original)).to.deep.equal(original);
});

testOmit('with hook.result', 'result');
testOmit('with hook.dispatch already set', 'dispatch');
});