This chapter applies only to TypeScript
Warning In this article, you'll learn how to create a
DatabaseModulebased on the TypeORM package from scratch using custom providers mechanism. As a consequence, this solution contains a lot of overhead that you can omit using ready to use and available out-of-the-box dedicated
@nestjs/typeormpackage. To learn more, see here.
TypeORM is definitely the most mature Object Relational Mapper (ORM) available in the node.js world. Since it's written in TypeScript, it works pretty well with the Nest framework.
To start the adventure with this library we have to install all required dependencies:
The first step we need to do is to establish the connection with our database using
createConnection() function imported from the
typeorm package. The
createConnection() function returns a
Promise, and therefore we have to create an async provider.
warning Warning Setting
synchronize: trueshouldn't be used in production - otherwise you can lose production data.
info Hint Following best practices, we declared the custom provider in the separated file which has a
Then, we need to export these providers to make them accessible for the rest of the application.
Now we can inject the
Connection object using
@Inject() decorator. Each class that would depend on the
Connection async provider will wait until a
Promise is resolved.
The TypeORM supports the repository design pattern, thus each entity has its own Repository. These repositories can be obtained from the database connection.
But firstly, we need at least one entity. We are going to reuse the
Photo entity from the official documentation.
Photo entity belongs to the
photo directory. This directory represents the
PhotoModule. Now, let's create a Repository provider:
warning Notice In the real-world applications you should avoid magic strings. Both
DATABASE_CONNECTIONshould be kept in the separated
Now we can inject the
Repository<Photo> to the
PhotoService using the
The database connection is asynchronous, but Nest makes this process completely invisible for the end-user. The
PhotoRepository is waiting for the db connection, and the
PhotoService is delayed until repository is ready to use. The entire application can start when each class is instantiated.
Here is a final
warning Hint Do not forget to import the
PhotoModuleinto the root