NestJS 配置 TypeORM 进阶教程

简介: 本文介绍了在 NestJS 项目中配置 TypeORM 的三种方式:初级阶段直接在 AppModule 中配置;进阶阶段抽离出独立的 DatabaseModule;进一步使用自定义命名空间将数据库配置分离到单独文件,提升可维护性与模块化程度。

初级:在 AppModule 直接配置 TypeORM

1. 安装依赖

首先,安装 NestJS、TypeORM 以及 MySQL 驱动:

pnpm install @nestjs/typeorm typeorm mysql2 @nestjs/config

2. 创建 .env 文件

在项目根目录下创建 .env 文件,用于存储数据库配置信息:

DB_TYPE=mysql
DB_HOST=localhost
DB_PORT=3306
DB_USERNAME=root
DB_PASSWORD=123456
DB_NAME=login_nest
DB_SYNCHRONIZE=false
DB_LOG=true

3. 配置 AppModule

app.module.ts 中直接配置 TypeORM:

app.module.tsApplyimport { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from '@nestjs/config';
import * as path from 'path';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
    }),
    TypeOrmModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        type: configService.get<string>('DB_TYPE', 'mysql'),
        host: configService.get<string>('DB_HOST', 'localhost'),
        port: configService.get<number>('DB_PORT', 3306),
        username: configService.get<string>('DB_USERNAME', 'root'),
        password: configService.get<string>('DB_PASSWORD', '123456'),
        database: configService.get<string>('DB_NAME', 'login_nest'),
        entities: [path.join(__dirname, '../common/entities/*.entity{.ts,.js}')],
        synchronize: configService.get<boolean>('DB_SYNCHRONIZE', false),
        logging: configService.get<boolean>('DB_LOG', true),
        autoLoadEntities: true,
      }),
    }),
    // 其他模块
  ],
  // 其他配置
})
export class AppModule {}

进阶:抽离 DatabaseModule 单独配置

1. 创建 DatabaseModule

src/database 目录下创建 database.module.ts 文件:

database.module.tsApplyimport { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigService } from '@nestjs/config';
import * as path from 'path';

@Module({
  imports: [
    TypeOrmModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        type: configService.get<string>('DB_TYPE', 'mysql'),
        host: configService.get<string>('DB_HOST', 'localhost'),
        port: configService.get<number>('DB_PORT', 3306),
        username: configService.get<string>('DB_USERNAME', 'root'),
        password: configService.get<string>('DB_PASSWORD', '123456'),
        database: configService.get<string>('DB_NAME', 'login_nest'),
        entities: [path.join(__dirname, '../../common/entities/*.entity{.ts,.js}')],
        synchronize: configService.get<boolean>('DB_SYNCHRONIZE', false),
        logging: configService.get<boolean>('DB_LOG', true),
        autoLoadEntities: true,
      }),
    }),
  ],
  exports: [TypeOrmModule],
})
export class DatabaseModule {}

2. 在 AppModule 中引入 DatabaseModule

修改 app.module.ts 文件:

app.module.tsApplyimport { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { DatabaseModule } from './database/database.module';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
    }),
    DatabaseModule,
    // 其他模块
  ],
  // 其他配置
})
export class AppModule {}

进一步:使用自定义命名空间 databaseToken 抽离配置到单独文件

1. 创建数据库配置文件

src/config 目录下创建 database.config.ts 文件:

import { registerAs } from '@nestjs/config';

export const databaseToken = 'database';

console.log('数据库类型', process.env.DB_TYPE);

// 使用 registerAs 函数注册自定义命名空间
//registerAs 函数本身不能使用 ConfigService 读取变量,这是由于 NestJS 配置加载的顺序决定的,此处使用process.env
export const databaseConfig = registerAs(databaseToken, () => ({
  type: process.env.DB_TYPE,
  host: process.env.DB_HOST,
  port: process.env.DB_PORT,
  username: process.env.DB_USERNAME,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  entities: [__dirname + '/../../common/entities/*.entity{.ts,.js}'],
  synchronize: process.env.DB_SYNCHRONIZE === 'true' || false,
  logging: process.env.DB_LOG === 'true' || false,
  autoLoadEntities: true,
}));

2. 修改 DatabaseModule

database.module.tsApplyimport { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigService } from '@nestjs/config';
import { databaseToken, databaseConfig } from '../config/database.config';

@Module({
  imports: [
    TypeOrmModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => {
        const dbConfig = configService.get(databaseToken);
        return dbConfig;
      },
    }),
  ],
  exports: [TypeOrmModule],
})
export class DatabaseModule {}

3. 在 AppModule 中加载数据库配置

必须在ConfigModule使用 forRoot() 方法的 options 对象的 load 属性加载命名空间配置

app.module.tsApplyimport { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { DatabaseModule } from './database/database.module';
import { databaseConfig } from './config/database.config';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      load: [databaseConfig],
    }),
    DatabaseModule,
    // 其他模块
  ],
  // 其他配置
})
export class AppModule {}

通过以上三个阶段,可以逐步优化 NestJS 项目中 TypeORM 的配置,让代码结构更清晰,更易于维护。

目录
相关文章
|
JSON 数据格式
Nestjs(三)接收参数 @Query @Body @Param(post、get 、put、delete ...)
Nestjs(三)接收参数 @Query @Body @Param(post、get 、put、delete ...)
1089 4
|
8月前
|
关系型数据库 测试技术 API
NestJS中TypeORM的使用
本文介绍了在 NestJS 中使用 TypeORM 实现数据库的 CRUD 操作,涵盖依赖安装、模块配置、实体定义、服务逻辑、控制器路由及 API 测试等步骤。
278 4
|
4月前
|
弹性计算 监控 安全
如何通过阿里云服务器部署Web应用?
阿里云提供ECS与SAE一站式Web应用部署方案,支持弹性伸缩、安全防护与全球加速,助力电商、教育等高并发业务稳定运行。四步完成环境搭建、应用发布与智能运维,结合真实案例验证可靠性。
|
8月前
|
JavaScript
TypeOrmModule 从 app.module.ts 抽离到 database.module.ts 后出现错误的原因分析
本文分析了TypeORM实体元数据错误的成因,主要涉及实体注册方式、路径解析差异及模块结构变化导致的关系解析问题,并提供了具体解决方案和最佳实践建议。
195 56
|
8月前
|
关系型数据库 MySQL
MySQL数据表添加字段(三种方式)
本文解析了数据表的基本概念及字段添加方法。在数据表中,字段是纵向列结构,记录为横向行数据。MySQL通过`ALTER TABLE`指令支持三种字段添加方式:1) 末尾追加字段,直接使用`ADD`语句;2) 首列插入字段,通过`FIRST`关键字实现;3) 指定位置插入字段,利用`AFTER`指定目标字段。文内结合`student`表实例详细演示了每种方法的操作步骤与结构验证,便于理解与实践。
|
存储 弹性计算 数据管理
阿里云对象存储OSS收费标准:存储、流量和请求等多个计费项详解
阿里云对象存储OSS提供多样化的计费模式,涵盖存储、流量、请求等多项费用。存储费用方面,按量付费标准型为0.09元/GB/月,包年包月则有9元40GB等多种选择。流量费用仅对公网出方向收费,价格区间从0.25至0.50元/GB不等,支持按量付费与流量包抵扣两种方式。更多详情及精准报价,欢迎访问阿里云OSS官方页面。
7550 1
|
JavaScript 前端开发 Python
浅谈PyExecJS模块
浅谈PyExecJS模块
284 5
|
存储 弹性计算 物联网
阿里云代金券、提货券、优惠券、储值卡领取及使用常见问题汇总
阿里云代金券、优惠券、提货券、储值卡是是阿里云最常见的几个优惠券种,官方发布这些券种的目的旨在为更多用户提供优惠上云的福利,代金券、优惠券、提货券、储值卡在性质及领取和使用上既有相同也有不同,下面是小编根据官方2024年的文档资料整理汇总的阿里云代金券、优惠券、提货券、储值卡领取及使用常见问题。
阿里云代金券、提货券、优惠券、储值卡领取及使用常见问题汇总