diff --git a/packages/feathers/src/hooks/legacy.ts b/packages/feathers/src/hooks/legacy.ts index 041ac6b08b..205248943b 100644 --- a/packages/feathers/src/hooks/legacy.ts +++ b/packages/feathers/src/hooks/legacy.ts @@ -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; + }); } } @@ -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(() => { diff --git a/packages/feathers/test/hooks/hooks.test.ts b/packages/feathers/test/hooks/hooks.test.ts index a6ecd6fb9b..8938a6b9be 100644 --- a/packages/feathers/test/hooks/hooks.test.ts +++ b/packages/feathers/test/hooks/hooks.test.ts @@ -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' + }); + }); });