Seeding
To end the core module, let's allow for the insertion of a bunch of fictional data to see the database populated.
Seeding is about either loading the database with mocked entities and relations between them to test the system's functionalities, or setting predefined data for the production environment. Here, we'll use it for the former reason.
TypeORM currently has no support for seeding, so we can write a route for doing such. For organization, let's create a very simple seeding resource inside the database structure. Choose no for CRUD entry points.
In the controller, insert the route responsible for seeding.
In the service, we need to perform several database operations and all of them need to be successful. In case any of them fails, all of the already performed operations need to be reverted back in order to avoid inconsistencies. This means that we need to use a transaction.
To do so, first we need to inject in the service a DataSource
.
Now, inside the seed()
method, insert the basic transaction structure inside which we'll put the actual seed. You can consider this as boilerplate.
The queryRunner
offers full control over the transaction, but we can also use a simpler approach that doesn't require using it, if possible. We should simply replace the boilerplate with this:
Now, we can use the seed itself. The following steps occur:
First, repositories are obtained from the
manager
. Only these repositories are able to rollback in case of a failed operation.After that, the database tables are cleared. Note that some of them are not cleared directly because their records will be deleted due to
cascade
.Finally, the entities and their relationships are created and saved in the database.
In the Extra module 6 - Automated Testing, we'll learn how to perform similar operations by simulating requests from a user. This is possible with the supertest library. We'll also do so in a dedicated database purposed for testing.
Commit - Seeding
Last updated