Class 04: Kết nối Database với TypeORM
NestJS tích hợp rất tốt với TypeORM – một ORM mạnh mẽ cho TypeScript hỗ trợ PostgreSQL, MySQL, SQLite... Bài học này sẽ giúp bạn biết cách cấu hình cơ bản, tạo Entity, Repository, thực hiện Migration, và truy vấn dữ liệu thực tế với bảng users.
Cấu hình kết nối cơ sở dữ liệu PostgreSQL/MySQL với TypeORM
Cài đặt package
Chạy lệnh sau tùy vào CSDL bạn chọn:
PostgreSQL:
npm install --save @nestjs/typeorm typeorm pgMySQL:
npm install --save @nestjs/typeorm typeorm mysql2Cấu hình TypeORM module
Trong file app.module.ts, thêm:
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UsersModule } from './users/users.module';
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'postgres', // hoặc 'mysql'
host: 'localhost',
port: 5432, // với MySQL là 3306
username: 'postgres', // hoặc 'root' với MySQL
password: 'password',
database: 'testdb',
autoLoadEntities: true,
synchronize: true, // chỉ dùng trong phát triển, KHÔNG dùng production
}),
UsersModule,
],
})
export class AppModule {}Giải thích các tuỳ chọn
type: Loại CSDL (postgres,mysql,sqlite, v.v.)autoLoadEntities: Tự động load các entity từ modulesynchronize: Tự động tạo bảng khi khởi động (chỉ dùng cho dev)entities: Có thể dùng thủ công để khai báo entity
Tạo Entity và Repository
Tạo Entity User
UserĐăng ký Entity vào Module
Sử dụng Repository trong Service
Migration cơ bản với TypeORM CLI
Cài đặt CLI
Thêm file ormconfig.ts:
Thêm script vào package.json:
Tạo và chạy migration
Migration giúp bạn kiểm soát schema DB một cách chặt chẽ, nhất là khi dùng trong production.
Bài tập thực hành
Mục tiêu
Xây dựng một module quản lý người dùng (users) kết nối với cơ sở dữ liệu PostgreSQL hoặc MySQL.
Yêu cầu
Cấu hình kết nối với database
Tạo
Userentity cóid,name,ageViết service với các chức năng:
Thêm người dùng mới
Lấy danh sách người dùng
Lấy người dùng theo
idCập nhật thông tin người dùng
Xoá người dùng
Thêm route tương ứng trong controller
Viết một migration tạo bảng
users
Gợi ý
Dùng
Postmanđể test các APIDùng
typeorm migration:generateđể tạo migrationNếu rảnh, thêm trường
email,createdAt
Last updated