Skip to content

Commit

Permalink
add hooks with args
Browse files Browse the repository at this point in the history
  • Loading branch information
jacoobes committed Jul 4, 2024
1 parent 130a3ec commit 28a76e4
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 3 deletions.
2 changes: 1 addition & 1 deletion packages/ioc/package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
4 changes: 2 additions & 2 deletions packages/ioc/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Expand Down
24 changes: 24 additions & 0 deletions packages/ioc/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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 = {
Expand Down

0 comments on commit 28a76e4

Please sign in to comment.