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

7,984 阅读2分钟

概述

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

使用示例

  1. 首先在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',
        },
    }
    
  2. 然后在ormconfig.ts导入设置,作用是在使用typeorm migration:generateTypeOrm命令时会使用到这个文件,作为连接数据库的配置。 在TypeOrm官方文档中提到可以使用ormconfig.jsonormconfig.js或者ormconfig.ts的方式来设置数据库连接,此处我们选择灵活度更高的ts文件形式。

    import { DataBaseConfig } from 'config/database'
    
    module.exports = DataBaseConfig
    

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

    {
        "include": [
            "ormconfig.ts",
            ...
        ],
        ...
    }
    
  3. app.module.ts导入设置,使用TypeOrmModule.forRoot(), 在NestJS框架中,连接到数据库。之后,ConnectionEntityManager就可以注入到程序中。 官方文档中提到,如果在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 {}
    
  4. 在具体的模块中,通过以下代码,在当前模块下,注册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 {}
    
  5. 随后,可以在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();
         }
     }
    

推荐规范

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