Trong NestJS, Service là nơi xử lý business logic — logic nghiệp vụ, không nên để trong Controller. Điều này giúp code dễ bảo trì, kiểm thử và mở rộng.
Tạo Service
NestJS cho phép bạn tạo service bằng CLI:
nest generate service users
Sử dụng Service trong Controller
Giả sử bạn có một service UsersService chứa logic xử lý:
new ValidationPipe({
whitelist: true, // loại bỏ các field không khai báo trong DTO
forbidNonWhitelisted: true, // báo lỗi nếu có field lạ
transform: true, // tự động chuyển từ JSON sang class
});
Thực hành: Validate dữ liệu người dùng với DTO + Pipe
Bước 1: Tạo DTO
// dto/create-user.dto.ts
import { IsEmail, IsNotEmpty, MinLength } from 'class-validator';
export class CreateUserDto {
@IsNotEmpty({ message: 'Tên không được để trống' })
name: string;
@IsEmail({}, { message: 'Email không hợp lệ' })
email: string;
@MinLength(6, { message: 'Mật khẩu tối thiểu 6 ký tự' })
password: string;
}
Bước 2: Cập nhật service
// users.service.ts
import { Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
@Injectable()
export class UsersService {
private users: CreateUserDto[] = [];
create(user: CreateUserDto) {
this.users.push(user);
return {
message: 'Tạo người dùng thành công',
user,
};
}
findAll() {
return this.users;
}
}