1. 创建项目
bash
nest new nest-mysql-test
2. 添加config
安装 @nestjs/config 包
bash
pnpm i --save @nestjs/config
添加 .env 文件
DATABASE_HOST=localhost
DATABASE_PORT=3306
DATABASE_USERNAME=root
DATABASE_PASSWORD=123456
DATABASE_DB=dbtest
创建 config/database.config.ts 文件
javascript
import { registerAs } from '@nestjs/config';
export default registerAs('database', () => ({
type: process.env.DATABASE_TYPE || 'mysql',
host: process.env.DATABASE_HOST || 'localhost',
port: parseInt(process.env.DATABASE_PORT, 10) || 3306,
username: process.env.DATABASE_USERNAME,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE_DB,
}));
添加 common 模块
bash
nest g module common
修改 common.module.ts
javascript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import databseConfig from 'src/config/databse.config';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
load: [databseConfig],
}),
],
})
export class CommonModule {}
3. 添加typeorm
安装依赖包
bash
pnpm install --save @nestjs/typeorm typeorm mysql2
修改 common.module.ts
javascript
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import databseConfig from 'src/config/databse.config';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
load: [databseConfig],
}),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
...configService.get('database'),
entities: [],
autoLoadEntities: true,
synchronize: true,
}),
}),
],
})
export class CommonModule {}
4. 添加实体
创建 entity/user.entity.ts 文件
javascript
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
firstName: string;
@Column()
lastName: string;
@Column({ default: true })
isActive: boolean;
}
在 common 模块中引入 user 实体
javascript
import { User } from '../entity/user.entity';
@Module({
imports: [
...
TypeOrmModule.forRootAsync({
...
useFactory: (configService: ConfigService) => ({
...
entities: [User],
}),
}),
],
})
export class CommonModule {}