SQL (Sequelize)¶
本章仅适用于打字稿¶
Warning
在本文中,您将学习如何使用自定义组件从头创建基于 Sequelize 包的DatabaseModule。
因此,这种技术包含了大量的开销,你可以通过使用专用的、开箱即用的@nestjs/sequelize包来避免。
要了解更多信息,请参见这里。
Sequelize is a popular Object Relational Mapper (ORM) written in a vanilla JavaScript, but there is a sequelize-typescript TypeScript wrapper which provides a set of decorators and other extras for the base sequelize.
入门¶
To start the adventure with this library we have to install the following dependencies:
The first step we need to do is create a Sequelize instance with an options object passed into the constructor. Also, we need to add all models (the alternative is to use modelPaths property) and sync() our database tables.
Hint
Following best practices, we declared the custom provider in the separated file which has a *.providers.ts suffix.
Then, we need to export these providers to make them accessible for the rest part of the application.
Now we can inject the Sequelize object using @Inject() decorator. Each class that would depend on the Sequelize async provider will wait until a Promise is resolved.
模型注入¶
In Sequelize the Model defines a table in the database. Instances of this class represent a database row. Firstly, we need at least one entity:
The Cat entity belongs to the cats directory. This directory represents the CatsModule. Now it's time to create a Repository provider:
Warning
In the real-world applications you should avoid magic strings . Both CATS_REPOSITORY and SEQUELIZE should be kept in the separated constants.ts file.
In Sequelize, we use static methods to manipulate the data, and thus we created an alias here.
Now we can inject the CATS_REPOSITORY to the CatsService using the @Inject() decorator:
The database connection is asynchronous , but Nest makes this process completely invisible for the end-user. The CATS_REPOSITORY provider is waiting for the db connection, and the CatsService is delayed until repository is ready to use. The entire application can start when each class is instantiated.
Here is a final CatsModule:
Hint
Do not forget to import the CatsModule into the root AppModule.