全书目录

第七篇:NestJS 完全指南 —— 国际机场总调度宇宙

第十四章:数据库边界 —— TypeORM 和 Prisma 都能用,但心智完全不同

1 分钟 380 字 第 194 / 962 个阅读单元

NestJS 并不强制数据库方案。
这反而是它的强项:框架负责工程结构,数据层你自己选。

#1. TypeORM 路线 —— 更像传统档案馆接口体系

官方 @nestjs/typeorm 集成路线大概这样:

ts
// app.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Flight } from './flights/flight.entity';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'postgres',
      host: 'localhost',
      port: 5432,
      username: 'airport',
      password: 'airport',
      database: 'airport',
      entities: [Flight],
      synchronize: false,
    }),
  ],
})
export class AppModule {}
ts
// flights.module.ts
@Module({
  imports: [TypeOrmModule.forFeature([Flight])],
  controllers: [FlightsController],
  providers: [FlightsService],
})
export class FlightsModule {}
ts
// flights.service.ts
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

@Injectable()
export class FlightsService {
  constructor(
    @InjectRepository(Flight)
    private readonly flightsRepository: Repository<Flight>,
  ) {}

  findAll() {
    return this.flightsRepository.find();
  }
}

TypeORM 心智:

  • 实体类
  • repository 注入
  • 偏传统 ORM
  • 和 Nest 模块化集成很顺
#2. Prisma 路线 —— 更像现代高铁调度台,类型体验很强

Nest 官方 Recipes 里也有 Prisma。

常见做法是自己封装一个 PrismaService

ts
import { INestApplication, Injectable, OnModuleInit } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';

@Injectable()
export class PrismaService
  extends PrismaClient
  implements OnModuleInit
{
  async onModuleInit() {
    await this.$connect();
  }

  async enableShutdownHooks(app: INestApplication) {
    process.on('beforeExit', async () => {
      await app.close();
    });
  }
}

业务层直接用:

ts
@Injectable()
export class FlightsService {
  constructor(private readonly prisma: PrismaService) {}

  findAll() {
    return this.prisma.flight.findMany();
  }
}

Prisma 心智:

  • schema 驱动
  • 自动生成类型安全 client
  • 查询 API 更现代
  • 很适合 TS 团队
#3. 真正该怎么选
text
TypeORM
├── 更像传统 ORM
├── 仓储/repository 心智明显
└── 很多 Java/.NET 背景同学更熟悉

Prisma
├── schema + generated client
├── 类型体验通常更强
└── 在现代 TS 项目里非常常见

真正重要的不是“哪家更神”,而是:

同一个项目里不要一会儿 TypeORM,一会儿 Prisma,把数据层搞成双轨制。