Skip to content

Commit

Permalink
fix: New factory binding doesn't reset a cached value
Browse files Browse the repository at this point in the history
  • Loading branch information
mnasyrov committed Jul 11, 2024
1 parent 71f63a9 commit 7a33dc6
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
40 changes: 40 additions & 0 deletions packages/ditox/src/container.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,46 @@ describe('Container', () => {
expect(container.get(CONTAINER)).toBe(container);
expect(container.get(PARENT_CONTAINER)).toBe(parent);
});

it('should rebind a value binding by the same token', () => {
const container = createContainer();

container.bindValue(NUMBER, 1);
container.bindFactory(NUMBER, () => 2);
expect(container.get(NUMBER)).toBe(2);
});

it('should rebind a factory binding by the same token', () => {
const container = createContainer();

container.bindFactory(NUMBER, () => 1);
container.bindFactory(NUMBER, () => 2);
expect(container.get(NUMBER)).toBe(2);
});

it('should reset a cached value during rebinding a factory', () => {
const container = createContainer();

container.bindFactory(NUMBER, () => 1);
expect(container.get(NUMBER)).toBe(1);

container.bindFactory(NUMBER, () => 2);
expect(container.get(NUMBER)).toBe(2);
});

it('should not reset a cached value if the factory is the same', () => {
const container = createContainer();

let value = 1;
const factory = () => value;

container.bindFactory(NUMBER, factory);
expect(container.get(NUMBER)).toBe(1);

value = 2;
container.bindFactory(NUMBER, factory);
expect(container.get(NUMBER)).toBe(1);
});
});

describe('remove()', () => {
Expand Down
12 changes: 11 additions & 1 deletion packages/ditox/src/container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,17 @@ export function createContainer(parentContainer?: Container): Container {
return;
}

factories.set(token.symbol, {factory, options});
const prev = factories.get(token.symbol);
const next = {factory, options};

const isSame =
prev && prev.factory === next.factory && prev.options === options;

if (!isSame) {
values.delete(token.symbol);
}

factories.set(token.symbol, next);
},

remove<T>(token: Token<T>): void {
Expand Down

0 comments on commit 7a33dc6

Please sign in to comment.