add hooks with args

This commit is contained in:
Jacob Nguyen
2024-07-04 11:54:39 -05:00
parent 130a3ece47
commit 28a76e460d
3 changed files with 27 additions and 3 deletions

View File

@@ -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",

View File

@@ -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);
}
}

View File

@@ -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 = {