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
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'
});
});
});