From 5dfe68647598aaa4649536395034ab96df3f874c Mon Sep 17 00:00:00 2001 From: Thodoris Greasidis Date: Thu, 18 May 2023 18:53:15 +0300 Subject: [PATCH] Add a PRERESPOND-ERROR hook Resolves: #665 Change-type: minor --- src/sbvr-api/hooks.ts | 13 +++++++++++-- src/sbvr-api/sbvr-utils.ts | 8 +++++++- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/src/sbvr-api/hooks.ts b/src/sbvr-api/hooks.ts index 186ce66f8..893a60467 100644 --- a/src/sbvr-api/hooks.ts +++ b/src/sbvr-api/hooks.ts @@ -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>>; @@ -68,6 +72,7 @@ const hookNames: Array = [ 'POSTRUN', 'PRERESPOND', 'POSTRUN-ERROR', + 'PRERESPOND-ERROR', ]; const isValidHook = (x: any): x is keyof Hooks => hookNames.includes(x); @@ -403,7 +408,7 @@ export const runHooks = async ( 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, @@ -423,7 +428,11 @@ export const runHooks = async ( 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 diff --git a/src/sbvr-api/sbvr-utils.ts b/src/sbvr-api/sbvr-utils.ts index 8886f03ae..62cbdcc1f 100644 --- a/src/sbvr-api/sbvr-utils.ts +++ b/src/sbvr-api/sbvr-utils.ts @@ -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); };