概述
TypeORM
是一个使用装饰器,对TypeScript
支持非常良好的ORM框架。在NestJS
中,可通过@nestjs/typeorm
,使用装饰器的方式优雅地使用TypeORM
。
使用示例
-
首先在
config/database.ts
导出数据库连接配置:export const DatabaseConfig = { type: 'mysql', host: '127.0.0.1', port: 3306, username: 'root', password: '123456', database: 'example', entities: [__dirname + '/**/*.entity{.ts,.js}'], synchronize: false, migrations: ['database/migration/**/*.ts'], cli: { migrationsDir: 'database/migration/default', }, }
-
然后在
ormconfig.ts
导入设置,作用是在使用typeorm migration:generate
等TypeOrm
命令时会使用到这个文件,作为连接数据库的配置。 在TypeOrm
官方文档中提到可以使用ormconfig.json
,ormconfig.js
或者ormconfig.ts
的方式来设置数据库连接,此处我们选择灵活度更高的ts文件形式。import { DataBaseConfig } from 'config/database' module.exports = DataBaseConfig
注意:请保证ormconfig.ts也在
tsconfig.json
的编译范围内:{ "include": [ "ormconfig.ts", ... ], ... }
-
在
app.module.ts
导入设置,使用TypeOrmModule.forRoot()
, 在NestJS
框架中,连接到数据库。之后,Connection
和EntityManager
就可以注入到程序中。 官方文档中提到,如果在ormconfig.json
写入配置作为forRoot()
的默认参数,由于我们使用的是ts文件,需要手动导入配置)import { Module } from '@nestjs/common' import { TypeOrmModule } from '@nestjs/typeorm' import { DataBaseConfig } from 'config/database' @Module({ imports: [TypeOrmModule.forRoot(DataBaseConfig)], }) export class ApplicationModule {}
-
在具体的模块中,通过以下代码,在当前模块下,注册
Repository
。(请先自行创建./example.entity
文件)import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { Example } from './example.entity'; @Module({ imports: [TypeOrmModule.forFeature([Example])], }) export class ExampleModule {}
-
随后,可以在service和controller等中用依赖注入的方式使用
Repository
。import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { Example } from './example.entity'; @Injectable() export class ExampleService { constructor( @InjectRepository(Example) public readonly repo: Repository<Example>, ) {} findAll(): Promise<Example[]> { return this.exampleRepo.find(); } }
推荐规范
- 推荐将数据库连接配置写在.env文件中,而不是采用
ormconfig.json
的方式。这样做的好处是把敏感信息统一在.env中管理。另外也方便拓展连接到多个数据库。如何读取配置文件详见另一文章【NestJS】配置信息与环境变量