E5E9 Turn argument validation into the first hook by daffl · Pull Request #818 · feathersjs/feathers · GitHub
[go: up one dir, main page]

Skip to content
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
17 changes: 8 additions & 9 deletions lib/hooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,6 @@ const hookMixin = exports.hookMixin = function hookMixin (service) {
const returnHook = args[args.length - 1] === true
? args.pop() : false;

// We have to try/catch this so that argument validation
// returns a rejected promise
try {
validateArguments(method, args);
} catch (e) {
return Promise.reject(e);
}

// A reference to the original method
const _super = service._super.bind(service);
// Create the hook object that gets passed through
Expand All @@ -51,7 +43,14 @@ const hookMixin = exports.hookMixin = function hookMixin (service) {
service,
app
});
const beforeHooks = getHooks(app, service, 'before', method);
// A hook that validates the arguments and will always be the very first
const validateHook = context => {
validateArguments(method, args);

return context;
};
// The `before` hook chain (including the validation hook)
const beforeHooks = [ validateHook, ...getHooks(app, service, 'before', method) ];

// Process all before hooks
return processHooks.call(service, beforeHooks, hookObject)
Expand Down
15 changes: 15 additions & 0 deletions test/hooks/hooks.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,21 @@ describe('hooks basics', () => {
});
});

it('on argument validation error', () => {
const app = feathers().use('/dummy', {
get (id) {
return Promise.resolve({ id });
}
});

return app.service('dummy').get(undefined, {}, true).catch(context => {
assert.equal(context.service, app.service('dummy'));
assert.equal(context.type, 'error');
assert.equal(context.path, 'dummy');
assert.equal(context.error.message, 'An id must be provided to the \'get\' method');
});
});

it('still swallows error if context.result is set', () => {
const result = { message: 'this is a test' };
const app = feathers().use('/dummy', {
Expand Down
0