发布于 2026-01-06 5 阅读
0

在 NestJS 中使用 TypeORM 建立 PostgreSQL 连接

在 NestJS 中使用 TypeORM 建立 PostgreSQL 连接

TypeORM + Postgres

在现代 Web 开发领域,构建可扩展且高效的应用程序需要扎实的数据库管理基础。PostgreSQL 是一款功能强大的开源关系型数据库管理系统,因其卓越的性能和可靠性而被广泛应用。当它与 NestJS 应用程序中的 TypeORM 库结合使用时,便能成为管理数据库连接和交互的强大工具。本文将指导您如何在 NestJS 环境中使用 TypeORM 建立 PostgreSQL 连接,包括使用 Docker 设置 PostgreSQL 数据库以及创建 Poll API 示例。

先决条件

在深入细节之前,请确保您的系统已安装以下工具和技术:

  1. Node.js 和 npm:用于运行 NestJS 应用程序。

  2. Docker:用于在 Docker 容器中设置 PostgreSQL 数据库。

  3. Nest CLI:用于生成和管理您的 NestJS 应用程序。

步骤 1:创建 NestJS 应用程序

我们先来创建一个新的 NestJS 应用。打开终端并执行以下命令:



nest new poll-api


Enter fullscreen mode Exit fullscreen mode

导航至项目目录:



cd poll-api


Enter fullscreen mode Exit fullscreen mode

步骤 2:安装 TypeORM 和 PostgreSQL 包

TypeORM 是一个流行的 TypeScript 和 JavaScript 对象关系映射 (ORM) 库。它允许开发人员使用 TypeScript 类和装饰器与数据库交互,从而简化数据库操作。

将 TypeORM 和 PostgreSQL 驱动程序作为项目依赖项安装:



npm install @nestjs/typeorm typeorm pg


Enter fullscreen mode Exit fullscreen mode

步骤 3:使用 Docker 设置 PostgreSQL 数据库

Docker 是创建隔离开发环境的必备工具。我们将使用 Docker 为我们的 NestJS 应用程序搭建 PostgreSQL 数据库服务器。

在项目根目录下创建 docker-compose.yml 文件:



version: '3.7'
services:
  postgres:
    image: postgres:13
    container_name: postgres_db
    ports:
      - '5432:5432'
    environment:
      POSTGRES_DB: poll_db
      POSTGRES_USER: poll_user
      POSTGRES_PASSWORD: poll_password
    volumes:
      - postgres_data:/var/lib/postgresql/data
volumes:
  postgres_data:


Enter fullscreen mode Exit fullscreen mode

此 Docker Compose 配置设置了一个名为 postgres_db 的 PostgreSQL 容器,其中包含一个名为 poll_db 的数据库、一个名为 poll_user 的用户以及关联的密码。

使用 Docker Compose 运行 PostgreSQL 容器:



docker compose up -d


Enter fullscreen mode Exit fullscreen mode

步骤 4:配置 TypeORM 连接

打开 src/app.module.ts 文件并配置 TypeORM 连接。导入必要的模块,并使用 PostgreSQL 连接选项配置 TypeOrmModule.forRoot() 方法:



import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'postgres',
      host: 'localhost',
      port: 5432,
      username: 'poll_user',
      password: 'poll_password',
      database: 'poll_db',
      entities: [],
      synchronize: true,
    }),
  ],
})
export class AppModule {}


Enter fullscreen mode Exit fullscreen mode

步骤 5:创建投票实体

在 src/poll 目录下创建 poll.entity.ts 文件。使用 TypeORM 装饰器定义 Poll 实体:



import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';

@Entity()
export class Poll {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  question: string;

  @Column('jsonb', { nullable: true })
  options: string[];
}


Enter fullscreen mode Exit fullscreen mode

步骤 6:创建轮询服务

在 src/poll 目录下创建 poll.service.ts 文件。实现 PollService 类,该类将负责与数据库交互:



import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Poll } from './poll.entity';

@Injectable()
export class PollService {
  constructor(
    @InjectRepository(Poll)
    private readonly pollRepository: Repository<Poll>,
  ) {}

  async createPoll(question: string, options: string[]): Promise<Poll> {
    const poll = this.pollRepository.create({ question, options });
    return this.pollRepository.save(poll);
  }

  async getAllPolls(): Promise<Poll[]> {
    return this.pollRepository.find();
  }
}


Enter fullscreen mode Exit fullscreen mode

步骤 7:创建轮询控制器

在 src/poll 目录下创建 poll.controller.ts 文件。实现 PollController 类,该类将处理与投票相关的传入 HTTP 请求:



import { Controller, Get, Post, Body } from '@nestjs/common';
import { PollService } from './poll.service';

@Controller('polls')
export class PollController {
  constructor(private readonly pollService: PollService) {}

  @Post()
  createPoll(@Body() { question, options }: { question: string; options: string[] }) {
    return this.pollService.createPoll(question, options);
  }

  @Get()
  getAllPolls() {
    return this.pollService.getAllPolls();
  }
}


Enter fullscreen mode Exit fullscreen mode

步骤 8:配置模块

再次打开 src/app.module.ts 文件并导入 PollController 和 PollService。



import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Poll } from './poll/poll.entity';
import { PollService } from './poll/poll.service';
import { PollController } from './poll/poll.controller';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      // ... (previous TypeORM config)
      entities: [Poll],
      synchronize: true,
    }),
    TypeOrmModule.forFeature([Poll]),
  ],
  providers: [PollService],
  controllers: [PollController],
})
export class AppModule {}


Enter fullscreen mode Exit fullscreen mode

步骤 9:测试 API

运行以下命令启动 NestJS 应用程序:



npm run start:dev


Enter fullscreen mode Exit fullscreen mode

现在您可以使用 curl 或 Postman 等工具访问 API 端点:

创建投票:POST http://localhost:3000/polls
请求正文:



{
  "question": "What's your favorite programming language?",
  "options": ["JavaScript", "Python", "Java", "C++"]
}


Enter fullscreen mode Exit fullscreen mode

获取所有投票:GET http://localhost:3000/polls

结论

在本详细指南中,我们学习了如何在 NestJS 应用程序中使用 TypeORM 建立 PostgreSQL 连接。我们使用 Docker 设置了 PostgreSQL 数据库,定义了 Poll 实体,创建了 Poll 服务,并实现了用于创建和检索投票的 API 端点。这些基础为使用 NestJS 框架、PostgreSQL 和 TypeORM 构建更复杂、功能更丰富的应用程序奠定了坚实的基础。

这里提供一个示例项目仓库的链接,以便更具体地演示本文讨论的概念:GitHub 仓库

文章来源:https://dev.to/vishnucprasad/etting-postgresql-connection-with-typeorm-in-nestjs-4le3