Skip to content

Commit

Permalink
Merge pull request #109 from feathersjs/validator-1
Browse files Browse the repository at this point in the history
Enhanced validate hook
  • Loading branch information
eddyystop authored Jan 18, 2017
2 parents 88a0a9a + 0bbed57 commit 49fd234
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 17 deletions.
2 changes: 1 addition & 1 deletion src/services/validate.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export default function (validator) {
throw new errors.BadRequest(`Expected validator function. (validate)`);
}

const results = validator(getItems(hook));
const results = validator(getItems(hook), hook);

if (results && typeof results.then === 'function') {
return results.then(convertedValues => {
Expand Down
40 changes: 24 additions & 16 deletions test/services/validate.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@ import { assert } from 'chai';
import hooks from '../../src/services';
import errors from 'feathers-errors';

var fcnSync;
var fcnPromise;
var fcnPromiseSanitize;
var origHookOk;
var origHookBad;
var hookOk;
var hookBad;
let fcnSync;
let fcnPromise;
let fcnPromiseSanitize;
let origHookOk;
let origHookBad;
let hookOk;
let hookBad;
let fcnHook;

describe('validate', () => {
origHookOk = { type: 'before', method: 'create', data: { email: ' [email protected] ' } };
Expand All @@ -19,16 +20,19 @@ describe('validate', () => {
beforeEach(() => {
hookOk = clone(origHookOk);
hookBad = clone(origHookBad);
fcnHook = {};

fcnSync = (values) => (values.email.trim() // eslint-disable-line no-unused-expressions
? null
: { email: 'Email is invalid' }
);
fcnSync = (values, hook) => {
fcnHook = hook;

return values.email.trim() ? null : { email: 'Email is invalid' };
}
});

it('test passes on correct data', () => {
const hook = hooks.validate(fcnSync)(hookOk);
assert.deepEqual(hook, origHookOk);
assert.deepEqual(fcnHook, origHookOk)
});

it('test fails on errors', () => {
Expand All @@ -40,16 +44,19 @@ describe('validate', () => {
beforeEach(() => {
hookOk = clone(origHookOk);
hookBad = clone(origHookBad);

fcnPromise = (values) => (
new Promise((resolve, reject) => {
fcnHook = {};

fcnPromise = (values, hook) => {
fcnHook = hook;

return new Promise((resolve, reject) => {
setTimeout(() => {
values.email.trim() // eslint-disable-line no-unused-expressions
? resolve()
: reject(new errors.BadRequest({ email: 'Email is invalid' }));
}, 100);
})
);
});
};

fcnPromiseSanitize = (values) => (
new Promise((resolve, reject) => {
Expand All @@ -66,6 +73,7 @@ describe('validate', () => {
hooks.validate(fcnPromise)(hookOk)
.then(hook => {
assert.deepEqual(hook, origHookOk);
assert.deepEqual(fcnHook, origHookOk);
next();
})
.catch(err => next(err));
Expand Down

0 comments on commit 49fd234

Please sign in to comment.