chore: well the book was obviously wrong.

permalink: http://whatthecommit.com/3f3725962c1b9d44b824736db7579209
This commit is contained in:
EvolutionX
2024-06-13 12:18:47 +05:30
parent 01597c83dd
commit 09ce86b67e
4 changed files with 19 additions and 9 deletions

View File

@@ -4,7 +4,7 @@
"description": "Dependency Injection system",
"main": "dist/index.js",
"scripts": {
"test": "vitest --run",
"test": "vitest --watch",
"tdd": "vitest",
"build": "tsc"
},

View File

@@ -82,14 +82,16 @@ export class Container {
const existing = this.__singletons.get(key);
if (!existing) {
// @jacoobes should we return false if no existing key?
throw Error("No existing key to swap for " + key);
return false;
}
// check if there's dispose hook, and call it
if (hasCallableMethod(existing, 'dispose')) {
this.disposeAll().then(() => {;
this.registerHooks('dispose', swp);
});
existing.dispose();
// get the index of the existing singleton, now delete the dispose hook at that index
const hookIndex = this.hooks.get('dispose')!.indexOf(existing.dispose);
if (hookIndex > -1) {
this.hooks.get('dispose')!.splice(hookIndex, 1);
}
}
this.__singletons.set(key, swp);

View File

@@ -125,8 +125,9 @@ describe('CoreContainer Tests', () => {
expect(singletonWInit.init).toHaveBeenCalledOnce();
});
it('should throw because not swapping anything', () => {
expect(() => coreContainer.swap('singletonKeyWithInit', singletonWInit)).toThrow()
it('should be false because not swapping anything', () => {
const swap = coreContainer.swap('singletonKeyWithInit', singletonWInit);
expect(swap).toBe(false);
})
it('should swap object with another', () => {
@@ -146,11 +147,18 @@ describe('CoreContainer Tests', () => {
dispose: vi.fn()
};
const singletonWithDispose3 = {
value: 'singletonValueWithDispose3',
dispose: vi.fn()
};
coreContainer.addSingleton('singletonWithDispose3', singletonWithDispose3);
const swapped = coreContainer.swap('singleton', singletonWithDispose2);
expect(singletonWDispose.dispose).toHaveBeenCalledOnce();
expect(coreContainer.get<Record<string, unknown>>('singleton')).toBe(singletonWithDispose2);
expect(singletonWithDispose2.dispose).not.toHaveBeenCalledOnce();
expect(singletonWithDispose3.dispose).not.toHaveBeenCalledOnce();
expect(swapped).toBe(true);
})
})

View File

@@ -2278,7 +2278,7 @@ __metadata:
"typescript@patch:typescript@^5.0.0#~builtin<compat/typescript>":
version: 5.4.5
resolution: "typescript@patch:typescript@npm%3A5.4.5#~builtin<compat/typescript>::version=5.4.5&hash=14eedb"
resolution: "typescript@patch:typescript@npm%3A5.4.5#~builtin<compat/typescript>::version=5.4.5&hash=f3b441"
bin:
tsc: bin/tsc
tsserver: bin/tsserver