Skip to content

Commit

Permalink
feat(container): add decorate to container
Browse files Browse the repository at this point in the history
  • Loading branch information
squirly committed Jun 28, 2019
1 parent b015122 commit e9d5924
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/Container.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,21 @@ interface Dep3 {
const Dep3 = Binding<Dep3>('Dep3');

describe('Container', () => {
describe('#decorate', () => {
it('adds dependencies in decorator', async () => {
const container = Container.create()
.bindFactory(Dep1, async c => ({
a: (await c.resolve(Dep2)).b.toString(),
}))
.decorate(c =>
c.bindFactory(Dep2, () => ({b: 2})).bindConstant(Dep3, {c: true}),
);

expect(await container.resolve(Dep1)).toHaveProperty('a', '2');
expect(await container.resolve(Dep3)).toHaveProperty('c', true);
});
});

describe('#bindFactory', () => {
it('calls the factory with the latest container container', async () => {
const container = Container.create()
Expand Down
12 changes: 12 additions & 0 deletions src/Container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ export class Container<Service> {
private readonly chain: Array<Resolution<Service>>,
) {}

decorate<S>(
decorator: Container.Decorator<S, Service>,
): Container<Service | S> {
return decorator(this);
}

bindFactory<S>(
{Tag: tag}: Binding<S>,
factory: Resolution<S>['factory'],
Expand Down Expand Up @@ -119,3 +125,9 @@ export interface Resolution<Service> {
tag: Binding.Tag<Service>;
factory: (container: Container<any>) => Service | Promise<Service>;
}

export namespace Container {
export type Decorator<Out, In> = (
container: Container<In>,
) => Container<In | Out>;
}
3 changes: 3 additions & 0 deletions src/Module.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import {Binding} from './Binding';
import {Container, Resolution} from './Container';

/**
* @deprecated Use container Decorators instead.
*/
export class Module<Export, Service = any> {
static create<Service>(
container: Container<Service>,
Expand Down

0 comments on commit e9d5924

Please sign in to comment.