Skip to content

Commit

Permalink
fix(hooks): Ensure that all error hooks are run (#103)
Browse files Browse the repository at this point in the history
  • Loading branch information
daffl authored Jun 4, 2022
1 parent ba99235 commit bbd1979
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
9 changes: 7 additions & 2 deletions main/hooks/src/regular.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export interface RegularHookMap {
error?: RegularMiddleware[];
}

const runHook = (hook: RegularMiddleware, context: any, type?: string) => {
export const runHook = (hook: RegularMiddleware, context: any, type?: string) => {
if (type) context.type = type;
return Promise.resolve(hook.call(context.self, context))
.then((res: any) => {
Expand All @@ -21,6 +21,11 @@ const runHook = (hook: RegularMiddleware, context: any, type?: string) => {
});
};

export const runHooks = (hooks: RegularMiddleware[]) => (context: any) => hooks.reduce(
(promise, hook) => promise.then(() => runHook(hook, context)),
Promise.resolve(context),
);

export function fromBeforeHook(hook: RegularMiddleware) {
return (context: any, next: any) => {
return runHook(hook, context, 'before').then(next);
Expand Down Expand Up @@ -56,7 +61,7 @@ export function collect(
) {
const beforeHooks = before.map(fromBeforeHook);
const afterHooks = [...after].reverse().map(fromAfterHook);
const errorHooks: any = error.map(fromErrorHook);
const errorHooks = error.length ? [fromErrorHook(runHooks(error))] : [];

return compose([...errorHooks, ...afterHooks, ...beforeHooks]);
}
7 changes: 6 additions & 1 deletion main/hooks/test/collect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,11 @@ it('collect: error hooks', async () => {
ctx.result = 'result from error hook';
}
},
(ctx) => {
if (ctx.result === 'result from error hook') {
ctx.result += '!';
}
},
],
});

Expand Down Expand Up @@ -140,5 +145,5 @@ it('collect: error hooks', async () => {
'in error hook',
);

assertStrictEquals(await service.create('result'), 'result from error hook');
assertStrictEquals(await service.create('result'), 'result from error hook!');
});

0 comments on commit bbd1979

Please sign in to comment.