【NestJS】如何优雅地使用TypeOrm连接到数据库

概述

  1. TypeORM 是一个使用装饰器,对TypeScript支持非常良好的ORM框架。在NestJS中,可通过@nestjs/typeorm,使用装饰器的方式优雅地使用TypeORM

使用示例

  1. 首先在config/database.ts导出数据库连接配置:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
复制代码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',
},
}
  1. 然后在ormconfig.ts导入设置,作用是在使用typeorm migration:generateTypeOrm命令时会使用到这个文件,作为连接数据库的配置。
    TypeOrm官方文档中提到可以使用ormconfig.jsonormconfig.js或者ormconfig.ts的方式来设置数据库连接,此处我们选择灵活度更高的ts文件形式。
1
2
3
复制代码import { DataBaseConfig } from 'config/database'

module.exports = DataBaseConfig

注意:请保证ormconfig.ts也在tsconfig.json的编译范围内:

1
2
3
4
5
6
7
复制代码{
"include": [
"ormconfig.ts",
...
],
...
}
  1. app.module.ts导入设置,使用TypeOrmModule.forRoot(), 在NestJS框架中,连接到数据库。之后,ConnectionEntityManager就可以注入到程序中。
    官方文档中提到,如果在ormconfig.json写入配置作为forRoot()的默认参数,由于我们使用的是ts文件,需要手动导入配置)
1
2
3
4
5
6
7
8
复制代码 import { Module } from '@nestjs/common'
import { TypeOrmModule } from '@nestjs/typeorm'
import { DataBaseConfig } from 'config/database'

@Module({
imports: [TypeOrmModule.forRoot(DataBaseConfig)],
})
export class ApplicationModule {}
  1. 在具体的模块中,通过以下代码,在当前模块下,注册Repository。(请先自行创建./example.entity文件)
1
2
3
4
5
6
7
8
复制代码import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Example } from './example.entity';

@Module({
imports: [TypeOrmModule.forFeature([Example])],
})
export class ExampleModule {}
  1. 随后,可以在service和controller等中用依赖注入的方式使用Repository
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
复制代码 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();
}
}

推荐规范

  1. 推荐将数据库连接配置写在.env文件中,而不是采用ormconfig.json的方式。这样做的好处是把敏感信息统一在.env中管理。另外也方便拓展连接到多个数据库。如何读取配置文件详见另一文章【NestJS】配置信息与环境变量

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%