Skip to content

Commit

Permalink
fix(hooks): Allow to set context.result to undefined (#70)
Browse files Browse the repository at this point in the history
  • Loading branch information
daffl authored Feb 8, 2021
1 parent 6c99cbd commit 7b5807f
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/hooks/src/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export function functionHooks <F> (fn: F, managerOrMiddleware: HookOptions) {

// Runs the actual original method if `ctx.result` is not already set
hookChain.push((ctx, next) => {
if (ctx.result === undefined) {
if (!Object.prototype.hasOwnProperty.call(context, 'result')) {
return Promise.resolve(original.apply(this, ctx.arguments)).then(result => {
ctx.result = result;

Expand Down
40 changes: 40 additions & 0 deletions packages/hooks/test/function.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,46 @@ describe('functionHooks', () => {
assert.strictEqual(res, 'Hello Dave');
});

it('can set context.result to undefined, skips method call, returns undefined', async () => {
const hello = async (_name: string) => {
throw new Error('Should never get here');
};
const updateResult = async (ctx: HookContext, next: NextFunction) => {
ctx.result = undefined;

await next();
};

const fn = hooks(hello, middleware([ updateResult ]));
const res = await fn('There');

assert.strictEqual(res, undefined);
});

it('deleting context.result, does not skip method call', async () => {
const hello = async (name: string) => {
return name;
};
const updateResult = async (ctx: HookContext, next: NextFunction) => {
ctx.result = 'Dave';

await next();
};
const deleteResult = async (ctx: HookContext, next: NextFunction) => {
delete ctx.result;

await next();
};

const fn = hooks(hello, middleware([
updateResult,
deleteResult
]));
const res = await fn('There');

assert.strictEqual(res, 'There');
});

it('can override context.result after', async () => {
const updateResult = async (ctx: HookContext, next: NextFunction) => {
await next();
Expand Down

0 comments on commit 7b5807f

Please sign in to comment.