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 loading the database with mocked entities and relations between them to test the system's functionalities.
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.
nest g res database/seeding
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 onefails, 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.
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:
await this.dataSource.transaction(async (manager) => {
// seed goes here
})
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.