0
0
Lập trình
Admin Team
Admin Teamtechmely

Hướng Dẫn Xây Dựng REST API với NestJS và Prisma (Phần 2): Triển Khai CRUD Cho Model Người Dùng

Đăng vào 3 tuần trước

• 4 phút đọc

Giới thiệu

Chào mừng bạn đến với phần 2 của bài hướng dẫn xây dựng REST API sử dụng NestJS và Prisma. Ở phần trước, chúng ta đã thực hiện các bước khởi tạo dự án NestJS, cài đặt Prisma để quản lý cơ sở dữ liệu, và tạo bảng User cùng với dữ liệu mẫu. Trong phần này, chúng ta sẽ cùng nhau triển khai các API CRUD (Create, Read, Update, Delete) cơ bản cho model User mà chúng ta đã xây dựng ở phần 1. 🤩

Triển khai API CRUD cho model User

Để triển khai API REST, trước tiên, bạn cần tạo tài nguyên (resources) cho model User. Điều này có thể thực hiện nhanh chóng bằng cách sử dụng Nest CLI. Hãy mở terminal và chạy lệnh sau:

Copy
npx nest generate resource

CLI sẽ yêu cầu bạn cung cấp một số thông tin:

Copy
$ npx nest generate resource
? What name would you like to use for this resource (plural, e.g., "users")? 
// Nhập users
? What transport layer do you use?
// Chọn option REST API
? Would you like to generate CRUD entry points? (Y/n)
// Y

Sau khi thực hiện lệnh trên, CLI sẽ tự động tạo tài nguyên User cùng với các thành phần cần thiết bên trong nó. Bạn sẽ tìm thấy thư mục src/users mới được tạo, trong đó có file src/users/users.controller.ts chứa định nghĩa của các routes (đường dẫn) và file src/users/users.service.ts để xử lý logic.

Thêm PrismaClient vào module User

Để có thể truy cập PrismaClient trong module User, bạn cần import PrismaModule như sau:

typescript Copy
import { PrismaModule } from './../prisma/prisma.module';
import { Module } from '@nestjs/common';
import { UsersService } from './users.service';
import { UsersController } from './users.controller';

@Module({
  controllers: [UsersController],
  providers: [UsersService],
  imports: [PrismaModule]
})
export class UsersModule {}

Sau khi thực hiện việc này, bạn có thể đưa PrismaService vào trong UsersService để sử dụng cho việc truy cập vào cơ sở dữ liệu. Hãy thêm constructor trong file src/users/users.service.ts:

typescript Copy
@Injectable()
export class UsersService {
  constructor(private prisma: PrismaService) {}

  create(createUserDto: CreateUserDto) {
    return 'This action adds a new user';
  }

  findAll() {
    return `This action returns all users`;
  }

  findOne(id: number) {
    return `This action returns a #${id} user`;
  }

  update(id: number, updateUserDto: UpdateUserDto) {
    return `This action updates a #${id} user`;
  }

  remove(id: number) {
    return `This action removes a #${id} user`;
  }
}

Định nghĩa các endpoint API

1. Định nghĩa GET /users endpoint

Controller cho endpoint này là findAll. Nó sẽ trả về tất cả các Users có trong cơ sở dữ liệu:

typescript Copy
@Get()
findAll() {
    return this.usersService.findAll();
}

Trong service:

typescript Copy
findAll() {
    return this.prisma.user.findMany();
}

Sử dụng findMany() để trả về tất cả các bản ghi users.

2. Định nghĩa GET /users/:id endpoint

Controller cho endpoint này là findOne. Endpoint này sẽ trả về một User có id tương ứng:

typescript Copy
@Get(':id')
findOne(@Param('id') id: string) {
    return this.usersService.findOne(+id);
}

Trong service:

typescript Copy
findOne(id: number) {
    return this.prisma.user.findUnique({where: {id}});
}

3. Định nghĩa POST /users endpoint

Đây là endpoint để tạo một User mới:

typescript Copy
@Post()
create(@Body() createUserDto: CreateUserDto) {
    return this.usersService.create(createUserDto);
}

Yêu cầu sẽ mong đợi body tương ứng với CreateUserDto. Hãy thiết lập DTO như sau:

typescript Copy
import { IsString, IsEmail, MaxLength, IsBoolean } from 'class-validator';

export class CreateUserDto {
    @IsString()
    @MaxLength(255)
    name: string;
  
    @IsEmail()
    email: string;
  
    @IsString()
    address?: string;

    @IsBoolean()
    isActive?: boolean = false;
}

Trong service:

typescript Copy
create(createUserDto: CreateUserDto) {
    return this.prisma.user.create({ data: createUserDto });
}

4. Định nghĩa PATCH /users/:id endpoint

Dùng để cập nhật một User hiện có:

typescript Copy
@Patch(':id')
update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {
    return this.usersService.update(+id, updateUserDto);
}

Trong service:

typescript Copy
update(id: number, updateUserDto: UpdateUserDto) {
    return this.prisma.user.update({ where: { id }, data: updateUserDto });
}

5. Định nghĩa DELETE /users/:id endpoint

Dùng để xóa một User hiện có:

typescript Copy
@Delete(':id')
remove(@Param('id') id: string) {
    return this.usersService.remove(+id);
}

Trong service:

typescript Copy
remove(id: number) {
    return this.prisma.user.delete({where: { id }});
}

Khi bạn gọi API xóa user (ví dụ: DELETE: http://localhost:8000/users/1) và sau đó gọi API để lấy tất cả users, bạn sẽ chỉ còn lại một user.

Kết luận

Chúc mừng bạn đã hoàn thành việc xây dựng một API REST đơn giản bằng NestJS! Trong hai phần bài viết, chúng ta đã khám phá những nội dung quan trọng sau đây:

  • Tổng quan về NestJS.
  • Khởi tạo một dự án NestJS.
  • Các bước xây dựng API REST với NestJS.
  • Tích hợp Prisma vào NestJS.

Việc phát triển API REST với NestJS và Prisma thật sự rất dễ dàng và hiệu quả. NestJS là một framework rất mạnh mẽ giúp bạn nhanh chóng xây dựng các ứng dụng web có cấu trúc tốt, an toàn và dễ bảo trì.

Xin cảm ơn bạn đã dành thời gian đọc bài viết này. Hẹn gặp lại bạn ở những chủ đề tiếp theo! 👋👋👋
source: viblo

Gợi ý câu hỏi phỏng vấn
Không có dữ liệu

Không có dữ liệu

Bài viết được đề xuất
Bài viết cùng tác giả

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào