Skip to content

Commit

Permalink
fix(core): Allow to return a new hook context in basic hooks (#2462)
Browse files Browse the repository at this point in the history
  • Loading branch information
daffl authored Oct 5, 2021
1 parent 9303e87 commit 422b6fc
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 10 deletions.
32 changes: 22 additions & 10 deletions packages/feathers/src/hooks/legacy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,37 @@ import { _ } from '../dependencies';
import { LegacyHookFunction } from '../declarations';

const { each } = _;
const mergeContext = (context: any) => (res: any) => {
if (res && res !== context) {
Object.assign(context, res);
}
return res;
}

export function fromBeforeHook (hook: LegacyHookFunction) {
return (context: any, next: any) => {
context.type = 'before';

return Promise.resolve(hook.call(context.self, context)).then(() => {
context.type = null;
return next();
});
return Promise.resolve(hook.call(context.self, context))
.then(mergeContext(context))
.then(() => {
context.type = null;
return next();
});
};
}

export function fromAfterHook (hook: LegacyHookFunction) {
return (context: any, next: any) => {
return next().then(() => {
context.type = 'after';
return hook.call(context.self, context)
}).then(() => {
context.type = null;
});
return next()
.then(() => {
context.type = 'after';
return hook.call(context.self, context)
})
.then(mergeContext(context))
.then(() => {
context.type = null;
});
}
}

Expand All @@ -38,6 +49,7 @@ export function fromErrorHooks (hooks: LegacyHookFunction[]) {

for (const hook of hooks) {
promise = promise.then(() => hook.call(context.self, context))
.then(mergeContext(context))
}

return promise.then(() => {
Expand Down
38 changes: 38 additions & 0 deletions packages/feathers/test/hooks/hooks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -354,4 +354,42 @@ describe('hooks basics', () => {
params: {}
});
});

it('allows to return new context in basic hooks (#2451)', async () => {
const app = feathers().use('/dummy', {
async get () {
return {};
}
});
const service = app.service('dummy');

service.hooks({
before: {
get: [
context => {
return {
...context,
value: 'something'
};
},
context => {
assert.strictEqual(context.value, 'something');
}
]
},
after: {
get: [context => {
context.result = {
value: context.value
}
}]
}
});

const data = await service.get(10);

assert.deepStrictEqual(data, {
value: 'something'
});
});
});

0 comments on commit 422b6fc

Please # to comment.