UNPKG

ts-ioc-container

Version:

Fast, lightweight TypeScript dependency injection container with a clean API, scoped lifecycles, decorators, tokens, hooks, lazy injection, customizable providers, and no global container objects.

40 lines (39 loc) 2.05 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.HooksRunner = void 0; const HookContext_1 = require("./HookContext"); const hook_1 = require("./hook"); const UnexpectedHookResultError_1 = require("../errors/UnexpectedHookResultError"); const promise_1 = require("../utils/promise"); class HooksRunner { key; constructor(key) { this.key = key; } execute(target, { scope, createContext = HookContext_1.createHookContext, mapContext = (context) => context, predicate = () => true, }) { const hooks = Array.from((0, hook_1.getHooks)(target, this.key).entries()).filter(([methodName]) => predicate(methodName)); const runMethodHooks = (methodName, executions) => { const context = mapContext(createContext(target, scope, methodName)); for (const execute of executions) { const result = execute(context); if (result instanceof Promise) { throw new UnexpectedHookResultError_1.UnexpectedHookResultError(`Hook ${methodName} returned a promise, use runHooksAsync instead`); } } }; for (const [methodName, executions] of hooks) { runMethodHooks(methodName, executions.map(hook_1.toHookFn)); } } async executeAsync(target, { scope, createContext = HookContext_1.createHookContext, mapContext = (context) => context, predicate = () => true, }) { const hooks = Array.from((0, hook_1.getHooks)(target, this.key).entries()).filter(([methodName]) => predicate(methodName)); const runMethodHooks = async (methodName, executions) => { const context = mapContext(createContext(target, scope, methodName)); for (const execute of executions) { await (0, promise_1.promisify)(execute(context)); } }; return Promise.all(hooks.map(([methodName, executions]) => runMethodHooks(methodName, executions.map(hook_1.toHookFn)))); } } exports.HooksRunner = HooksRunner;