From 28a76e460d1f8fc396980a48afbcbce5791251a1 Mon Sep 17 00:00:00 2001 From: Jacob Nguyen <76754747+jacoobes@users.noreply.github.com> Date: Thu, 4 Jul 2024 11:54:39 -0500 Subject: [PATCH] add hooks with args --- packages/ioc/package.json | 2 +- packages/ioc/src/index.ts | 4 ++-- packages/ioc/test/index.test.ts | 24 ++++++++++++++++++++++++ 3 files changed, 27 insertions(+), 3 deletions(-) diff --git a/packages/ioc/package.json b/packages/ioc/package.json index f067fbd..20da596 100644 --- a/packages/ioc/package.json +++ b/packages/ioc/package.json @@ -1,6 +1,6 @@ { "name": "@sern/ioc", - "version": "1.0.4", + "version": "1.1.0", "description": "Dependency Injection system", "main": "dist/index.js", "module": "./dist/index.js", diff --git a/packages/ioc/src/index.ts b/packages/ioc/src/index.ts index 08f5a39..2bc2d46 100644 --- a/packages/ioc/src/index.ts +++ b/packages/ioc/src/index.ts @@ -69,11 +69,11 @@ export class Container { return Object.fromEntries(this.__singletons) as T } - private async executeHooks(name: string) { + async executeHooks(name: string, args: any[] = []) { const hookFunctions = this.hooks.get(name) || []; for (const hookObject of hookFunctions) { //@ts-ignore .registerHooks verifies the hookObject hasCallableMethod - await hookObject[name](); + hookObject[name](...args); } } diff --git a/packages/ioc/test/index.test.ts b/packages/ioc/test/index.test.ts index 4921519..a312b4d 100644 --- a/packages/ioc/test/index.test.ts +++ b/packages/ioc/test/index.test.ts @@ -83,6 +83,27 @@ describe('CoreContainer Tests', () => { expect(initCount).toBe(1); }); + it('calls user defined hook', async () => { + class S { + schedule = vi.fn() + } + const s = new S() + coreContainer.addSingleton('abc', s) + coreContainer.addHook('schedule', s) + await coreContainer.executeHooks('schedule') + expect(s.schedule).toHaveBeenCalledOnce() + }) + + it('calls user defined hook with args', async () => { + class S { + schedule = vi.fn() + } + const s = new S() + coreContainer.addSingleton('abc', s) + coreContainer.addHook('schedule', s) + await coreContainer.executeHooks('schedule', ['a', 'b']) + expect(s.schedule).toHaveBeenNthCalledWith(1, 'a', 'b') + }) it('wired singleton', async () => { let fn = vi.fn() @@ -135,6 +156,9 @@ describe('CoreContainer Tests', () => { const swap = coreContainer.swap('singletonKeyWithInit', singletonWInit); expect(swap).toBe(false); }) + + + it('should return true because not swapping anything', () => { coreContainer.addSingleton('singletonKeyWithInit', singletonWInit); const singletonWithInit2 = {