Skip to content

Commit

Permalink
context: add @inject.getter
Browse files Browse the repository at this point in the history
Implement a new decorator for injecting a getter function to obtain
the bound value. This is useful when implementing Actions, where
the action is instantiated for Sequence constructor, but some
of action's dependencies become bound only after other actions
have been executed by the sequence.
  • Loading branch information
bajtos committed Aug 4, 2017
1 parent 421b063 commit 8b56d16
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
13 changes: 13 additions & 0 deletions packages/context/src/inject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,19 @@ export function inject(
};
}

export namespace inject {
export const getter = function injectGetter(
bindingKey: string,
metadata?: Object,
) {
return inject(bindingKey, metadata, resolveAsGetter);
};
}

function resolveAsGetter(ctx: Context, injection: Injection) {
return () => ctx.get(injection.bindingKey);
}

/**
* Return an array of injection objects for parameters
* @param target The target class for constructor or static methods,
Expand Down
21 changes: 21 additions & 0 deletions packages/context/test/acceptance/class-level-bindings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,27 @@ describe('Context bindings - Injecting dependencies of classes', () => {
);
});

it('injects a getter function', async () => {
ctx.bind('key').to('value');

class Store {
constructor(
@inject.getter('key')
public getter: Function,
) {}
}

ctx.bind('store').toClass(Store);
const store = ctx.getSync('store');

expect(store.getter).to.be.Function();
expect(await store.getter()).to.equal('value');

// rebind the value to verify that getter always returns a fresh value
ctx.bind('key').to('new-value');
expect(await store.getter()).to.equal('new-value');
});

function createContext() {
ctx = new Context();
}
Expand Down

0 comments on commit 8b56d16

Please sign in to comment.