Skip to content

Commit 73d9e06

Browse files
feat: add custom Continer provider
1 parent c2ae8a2 commit 73d9e06

File tree

2 files changed

+32
-6
lines changed

2 files changed

+32
-6
lines changed

src/container-provider.class.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { ContainedType, ContainerInterface, } from 'typeorm';
2+
import { Container, Constructable } from 'typedi';
3+
4+
/**
5+
* Class transforming between TypeDI API and the expected API by TypeORM.
6+
*/
7+
export class TypeDIContainerProvider implements ContainerInterface {
8+
get<T>(constructable: ContainedType<T>) {
9+
/**
10+
* TypeDI only resolves values for registered types, so we need to register
11+
* them before to requesting them from the default container.
12+
*/
13+
if (!Container.has(constructable as Constructable<T>)) {
14+
Container.set({ id: constructable, type: constructable as Constructable<T> });
15+
}
16+
17+
return Container.get(constructable as Constructable<T>);
18+
}
19+
}

src/index.ts

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,19 @@
1-
import { Container } from 'typedi';
1+
import { Container as TypeDIContainer } from 'typedi';
22
import { ConnectionManager } from 'typeorm';
3+
import { TypeDIContainerProvider } from './container-provider.class';
4+
5+
export * from './decorators/inject-connection.decorator';
6+
export * from './decorators/inject-manager.decorator';
7+
export * from './decorators/inject-repository.decorator';
38

49
/**
510
* We need to set imported TypeORM classes before requesting them, otherwise we
6-
* would receive a "ServiceNotFoundError" above TypeDI 0.9.1.
11+
* would receive a "ServiceNotFoundError" above TypeDI 0.9.1 from the decorators.
712
*/
8-
Container.set({ id: ConnectionManager, type: ConnectionManager });
13+
TypeDIContainer.set({ id: ConnectionManager, type: ConnectionManager });
914

10-
export * from './decorators/inject-connection.decorator';
11-
export * from './decorators/inject-manager.decorator';
12-
export * from './decorators/inject-repository.decorator';
15+
/**
16+
* We export the current container implementation what transforms function
17+
* calls between the TypeORM container format and TypeDI.
18+
*/
19+
export const Container = new TypeDIContainerProvider();

0 commit comments

Comments
 (0)