-
Notifications
You must be signed in to change notification settings - Fork 11
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: inject TypeOrm by InversifyJs #56
Conversation
a3abcf9
to
a983ffc
Compare
8520b5a
to
b22124f
Compare
Please add more tests, |
I can add a few tests because it need to connect to the database. Examples will be added after this pr merged. |
Functions/classes in |
OK, I will figure out how. |
Description
Inject TypeOrm by InversifyJs.
Usage
We assume that you are familiar with TypeOrm.
Install the required dependencies.
Define the
User
entity.Then bind the
Datasource
andEntityManager
to the container usingTypeOrmManager.importRoot()
, and they will be available to inject across the entire project.User
entity, we need to letTypeORM
know about it by inserting it into the entities array (unless you use a static glob path).TypeORM supports the repository design pattern, so each entity has its own repository. These repositories can be obtained from the database data source.
We can use
TypeOrmManager.importRepository()
to define which repositories are bound to the container. So the bound repositories will be also available to inject across the entire project.Let's define the
UserService
to operateUser
entities.Then we can inject the
DataSource
,EntityManager
orUsersRepository
into theUsersService
:DataSource
using the@InjectDataSource()
EntityManager
using the@InjectEntityManager()
UsersRepository
using the@InjectRepository()
And the
UserService
also needed to be bounded to the container by@Service()
, so that it can be created correctly by the container using the injectedDataSource
,EntityManager
orUsersRepository
.It's time to get the created
UserService
from the container bycontainer.get<UserService>(UserService.name)
and operateUser
entities!At last, you can close the connection with the database. Once connection is closed, you cannot use repositories or perform any operations except opening connection again.