Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(hooks): Update context.error in error hooks #107

Merged
merged 1 commit into from
Feb 7, 2023
Merged
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
40 changes: 25 additions & 15 deletions main/hooks/src/regular.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,19 @@ export interface RegularHookMap {
error?: RegularMiddleware[];
}

export const runHook = (hook: RegularMiddleware, context: any, type?: string) => {
export const runHook = (
hook: RegularMiddleware,
context: any,
type?: string,
) => {
const typeBefore = context.type;
if (type) context.type = type;
return Promise.resolve(hook.call(context.self, context))
.then((res: any) => {
if (type) context.type = typeBefore;
if (res && res !== context) {
Object.assign(context, res);
}
});
return Promise.resolve(hook.call(context.self, context)).then((res: any) => {
if (type) context.type = typeBefore;
if (res && res !== context) {
Object.assign(context, res);
}
});
};

export const runHooks = (hooks: RegularMiddleware[]) => (context: any) =>
Expand Down Expand Up @@ -49,18 +52,25 @@ export function fromErrorHook(hook: RegularMiddleware) {
delete context.result;
}

return runHook(hook, context, 'error').then(() => {
if (context.result === undefined && context.error !== undefined) {
return runHook(hook, context, 'error')
.then(() => {
if (context.result === undefined && context.error !== undefined) {
throw context.error;
}
})
.catch((error) => {
context.error = error;
throw context.error;
}
});
});
});
};
}

export function collect(
{ before = [], after = [], error = [] }: RegularHookMap,
) {
export function collect({
before = [],
after = [],
error = [],
}: RegularHookMap) {
const beforeHooks = before.map(fromBeforeHook);
const afterHooks = [...after].reverse().map(fromAfterHook);
const errorHooks = error.length ? [fromErrorHook(runHooks(error))] : [];
Expand Down