imp(core): ask context for lazy reader dependency and bootstrap it only once
MODIFY
packages/core/src/context/context.factory.ts
packages/core/src/context/context.factory.ts
@@ -43,11 +43,15 @@ export const registerAll = (boundDependencies: BoundDependency<any, any>[]) => (
);
export const lookup = (context: Context) => <T>(token: ContextToken<T>): Option<T> =>
- M.lookup(ordContextToken)(token, context).map(dependency =>
- isReader(dependency)
- ? dependency.run(context)
- : dependency
- );
+ M.lookup(ordContextToken)(token, context).map(dependency => {
+ if (!isReader(dependency)) {
+ return dependency;
+ }
+
+ const boostrapedDependency = dependency.run(context);
+ context.set(token, boostrapedDependency);
+ return boostrapedDependency;
+ });
export const bindTo =
<T>(token: ContextToken<T>) =>

MODIFY
packages/core/src/context/specs/context.factory.spec.ts
packages/core/src/context/specs/context.factory.spec.ts
@@ -124,6 +124,7 @@ describe('#reader', () => {
const dependency2 = reader.map(ask => ask(token1).map(v => v + '_1').getOrElse(''));
const dependency3 = reader.map(ask => ask(token2).map(v => v + '_2').getOrElse(''));
+ // when
const context = registerAll([
bindTo(token1)(dependency1),
bindTo(token2)(ctx => dependency2.run(ctx)),
@@ -135,4 +136,22 @@ describe('#reader', () => {
expect(lookup(context)(token2)).toEqual(some('test_1'));
expect(lookup(context)(token3)).toEqual(some('test_1_2'));
});
+
+ test('asks context for lazy reader dependency and bootstraps it only once', () => {
+ // given
+ const spy = jest.fn();
+ const token = createContextToken<string>();
+ const dependency = reader.map(() => { spy(); return 'test'; });
+
+ // when
+ const context = registerAll([
+ bindTo(token)(dependency),
+ ])(createContext());
+
+ // then
+ expect(lookup(context)(token)).toEqual(some('test'));
+ expect(lookup(context)(token)).toEqual(some('test'));
+ expect(lookup(context)(token)).toEqual(some('test'));
+ expect(spy).toHaveBeenCalledTimes(1);
+ });
});

imp(core): ask context for lazy reader dependency and bootstrap it only once