Skip to content

Commit

Permalink
Add a PRERESPOND-ERROR hook
Browse files Browse the repository at this point in the history
Resolves: #665
Change-type: minor
  • Loading branch information
thgreasi committed May 18, 2023
1 parent f94fca5 commit 5dfe686
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
13 changes: 11 additions & 2 deletions src/sbvr-api/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ export interface Hooks {
'POSTRUN-ERROR'?: (
options: HookArgs & { error: TypedError | any },
) => HookResponse;
/** These are run in reverse translation order from newest to oldest */
'PRERESPOND-ERROR'?: (
options: HookArgs & { error: TypedError | any },
) => HookResponse;
}
export type HookBlueprints = {
[key in keyof Hooks]: Array<HookBlueprint<NonNullable<Hooks[key]>>>;
Expand All @@ -68,6 +72,7 @@ const hookNames: Array<keyof Hooks> = [
'POSTRUN',
'PRERESPOND',
'POSTRUN-ERROR',
'PRERESPOND-ERROR',
];
const isValidHook = (x: any): x is keyof Hooks => hookNames.includes(x);

Expand Down Expand Up @@ -403,7 +408,7 @@ export const runHooks = async <T extends keyof Hooks>(
hookName: T,
/**
* A list of modelName/hooks to run in order, which will be reversed for hooks after the "RUN" stage,
* ie POSTRUN/PRERESPOND/POSTRUN-ERROR
* ie POSTRUN/PRERESPOND/POSTRUN-ERROR/PRERESPOND-ERROR
*/
hooksList: Array<[modelName: string, hooks: InstantiatedHooks]> | undefined,
args: RunHookArgs<T>,
Expand All @@ -423,7 +428,11 @@ export const runHooks = async <T extends keyof Hooks>(
if (hooks.length === 0) {
return;
}
if (['POSTRUN', 'PRERESPOND', 'POSTRUN-ERROR'].includes(hookName)) {
if (
['POSTRUN', 'PRERESPOND', 'POSTRUN-ERROR', 'PRERESPOND-ERROR'].includes(
hookName,
)
) {
// Any hooks after we "run" the query are executed in reverse order from newest to oldest
// as they'll be translating the query results from "latest" backwards to the model that
// was actually requested
Expand Down
8 changes: 7 additions & 1 deletion src/sbvr-api/sbvr-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1506,7 +1506,13 @@ const runRequest = async (
tx,
error: err,
});
throw err;
const httpError = convertToHttpError(err);
await runHooks('PRERESPOND-ERROR', request.hooks, {
req,
request,
error: httpError,
});
throw httpError;
}
return await prepareResponse(req, request, result, tx);
};
Expand Down

0 comments on commit 5dfe686

Please sign in to comment.