From bbd1979a1854441def03581bc248b11bb5fb1b2d Mon Sep 17 00:00:00 2001 From: David Luecke Date: Sat, 4 Jun 2022 10:23:56 -0700 Subject: [PATCH] fix(hooks): Ensure that all error hooks are run (#103) --- main/hooks/src/regular.ts | 9 +++++++-- main/hooks/test/collect.test.ts | 7 ++++++- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/main/hooks/src/regular.ts b/main/hooks/src/regular.ts index 0b13ab4..df1b254 100644 --- a/main/hooks/src/regular.ts +++ b/main/hooks/src/regular.ts @@ -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) => { @@ -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); @@ -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]); } diff --git a/main/hooks/test/collect.test.ts b/main/hooks/test/collect.test.ts index 4e1b847..ccdde18 100644 --- a/main/hooks/test/collect.test.ts +++ b/main/hooks/test/collect.test.ts @@ -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 += '!'; + } + }, ], }); @@ -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!'); });