|
| 1 | +import { EvaluationDetails, FlagValue, Hook, HookContext, HookHints, Logger } from '@openfeature/server-sdk'; |
| 2 | + |
| 3 | +/** |
| 4 | + * Utility for executing a set of hooks of each type. Implementation is largely copied from the main OpenFeature SDK. |
| 5 | + */ |
| 6 | +export class HookExecutor { |
| 7 | + constructor(private logger: Logger) {} |
| 8 | + |
| 9 | + async beforeHooks(hooks: Hook[] | undefined, hookContext: HookContext, hints: HookHints) { |
| 10 | + const newContext = { ...hookContext.context }; |
| 11 | + for (const hook of hooks ?? []) { |
| 12 | + // freeze the hookContext |
| 13 | + Object.freeze(hookContext); |
| 14 | + |
| 15 | + Object.assign(newContext, { |
| 16 | + ...(await hook?.before?.(hookContext, Object.freeze(hints))), |
| 17 | + }); |
| 18 | + } |
| 19 | + |
| 20 | + // after before hooks, freeze the EvaluationContext. |
| 21 | + return Object.freeze(newContext); |
| 22 | + } |
| 23 | + |
| 24 | + async afterHooks( |
| 25 | + hooks: Hook[] | undefined, |
| 26 | + hookContext: HookContext, |
| 27 | + evaluationDetails: EvaluationDetails<FlagValue>, |
| 28 | + hints: HookHints, |
| 29 | + ) { |
| 30 | + // run "after" hooks sequentially |
| 31 | + for (const hook of hooks ?? []) { |
| 32 | + await hook?.after?.(hookContext, evaluationDetails, hints); |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + async errorHooks(hooks: Hook[] | undefined, hookContext: HookContext, err: unknown, hints: HookHints) { |
| 37 | + // run "error" hooks sequentially |
| 38 | + for (const hook of hooks ?? []) { |
| 39 | + try { |
| 40 | + await hook?.error?.(hookContext, err, hints); |
| 41 | + } catch (err) { |
| 42 | + this.logger.error(`Unhandled error during 'error' hook: ${err}`); |
| 43 | + if (err instanceof Error) { |
| 44 | + this.logger.error(err.stack); |
| 45 | + } |
| 46 | + this.logger.error((err as Error)?.stack); |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + async finallyHooks(hooks: Hook[] | undefined, hookContext: HookContext, hints: HookHints) { |
| 52 | + // run "finally" hooks sequentially |
| 53 | + for (const hook of hooks ?? []) { |
| 54 | + try { |
| 55 | + await hook?.finally?.(hookContext, hints); |
| 56 | + } catch (err) { |
| 57 | + this.logger.error(`Unhandled error during 'finally' hook: ${err}`); |
| 58 | + if (err instanceof Error) { |
| 59 | + this.logger.error(err.stack); |
| 60 | + } |
| 61 | + this.logger.error((err as Error)?.stack); |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | +} |
0 commit comments