[EP.2] Nest.js + MySql (Service , Database)
![[EP.2] Nest.js + MySql (Service , Database)](/content/images/size/w960/2021/01/close-shot-cute-kitten-blanket.jpg)
ห่างหายกันมานาน เจ้าของบล๊อคงานยุ่งนิดหน่อยแต่ตอนนี้กลับมาทำแล้ว ใครยังไม่ได้อ่าน EP.1 ย้อนกลับไปดูได้นะครับ

เอาละเมื่อบทความที่แล้วเรา รุ้จัก controller , module กันไปแล้ว บทความนี้จะมาทำความรู้จักกับ Service และก็ เชื่อมต่อ Database กันนะครับ เพื่อที่จะทำ CRUD ของ users database
เชื่อต่อ Database ยังไง
การจะเชื่อมต่อ database ผมได้ใช้ตัวช่วยในการเชื่อมต่อหรือ Query ข้อมูลต่างๆ โดยใช้ library ที่ชื่อว่า Typeorm เป็น ตัวช่วยในการทำ database มาเริ่มกันเลย
ลง library กันก่อน
npm install --save @nestjs/typeorm typeorm mysql
สร้าง Service
หลังจากที่ลง library เสร็จจะมาทำการสร้าง Service ขึ้นมาหนึ่งตัว ชื่อว่า UserService พร้อมทั้ง Entity ที่จะเก็บข้อมูล User ลงใน database นะครับ
@Entity()
export class UserEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
}
@Injectable()
export class UserService {
constructor(
@InjectRepository(UserEntity)
private userRepository: Repository<UserEntity>,
) { }
findAll(): Promise<UserEntity[]> {
// Get All User
}
findOne() : Promise<UserEntity>{
// Get User
}
create(user : UserEntity): Promise<UserEntity> {
// Get Add User
}
async update(id: number, user: UserEntity) {
// Get Update User
}
async remove(id: number): Promise<void> {
// Get Delete
}
}
Service ตัวที่ทำการติดต่อกับ database จะไม่ใช้ Controllerในการติดต่อ
เราเตรียม service เสร็จแล้ว แต่ยังใช้งานไม่ได้เพราะเรายังไม่ได้นำมาใส่ใน Controller โดยการเพิ่ม Code ข้างล่างนี้ลงใน Controller
constructor(usersService: UsersService){}
จะเห็นว่ามันเป็นการ Injection ตัว Service เข้ามาใน UsersController จึงจำเป็นต้องกำหนดว่า Module นี้ ใช้ Service อะไรบ้าง โดยการเพิ่ม เข้าไปใน Module ตามนี้
@Module({
imports: [TypeOrmModule.forFeature([UserEntity])],
controllers: [UsersController],
providers: [UserService],
})
export class UsersModule {}
ต่อไป เรายังไม่ได้ Connect กับ Database เราต้องสั่งให้ App ต่อ Database โดยการเพิ่มลงไปตามนี้
@Module({
imports: [TypeOrmModule.forRoot({
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: 'root',
database: 'test',
entities: [UserEntity],
synchronize: true,
}), UsersModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule { }
เชื่อมต่อ Database ได้แล้ว เพียงเท่านี้เราก็ทำ CRUD ได้แล้ว
มาปรับ code สักหน่อย
@Injectable()
export class UserService {
constructor(
@InjectRepository(UserEntity)
private userRepository: Repository<UserEntity>,
) { }
findAll(): Promise<UserEntity[]> {
return this.userRepository.find();
}
findOne(id: number): Promise<UserEntity> {
return this.userRepository.findOne(id);
}
create(user: UserEntity): Promise<UserEntity> {
return this.userRepository.save(user);
}
async update(id: number, user: UserEntity) {
await this.userRepository.update(id, user)
}
async remove(id: number): Promise<void> {
await this.userRepository.delete(id);
}
}
@Controller('users')
export class UsersController {
constructor(private usersService: UserService) { }
@Get()
async findAll(@Res() res: Response) {
const response = await this.usersService.findAll()
res.status(HttpStatus.OK).json({ payload: response })
}
@Get(":id")
async findOne(@Param() id: number, @Res() res: Response) {
const response = await this.usersService.findOne(id)
res.status(HttpStatus.OK).json({ payload: response })
}
@Post()
async create(@Body() createUserDto: UserEntity, @Res() res: Response) {
const response = await this.usersService.create(createUserDto)
res.status(HttpStatus.OK).json({ payload: response })
}
@Put(":id")
async update(@Param() id: number, @Body() createUserDto: UserEntity, @Res() res: Response) {
this.usersService.update(id, createUserDto)
res.status(HttpStatus.OK).json({ message: "success" })
}
@Delete()
async delete(@Body() id: number, @Res() res: Response) {
this.usersService.remove(id)
res.status(HttpStatus.OK).json({ message: "success" })
}
}
เสร็จแล้วมาทดสอบกัน






จบไปแล้วนะครับกับบทความ CRUD ของ Nestjs ถ้าใครสนใจอยากจะเรียน รู้ Nestjs เพิ่มเติม ก็สามารถไปอ่าน docs ของ Nestjs ได้นะครับ ของเขาดีจริงๆ 555+
ปล. ถ้าเขียนไม่เข้าใจยังไง ก็ขออภัยด้วยนะครับ เจ้าของบล๊อคพิ่งจะหัดเขียนบทความ :) จะพยายามเขียนบทความขึ้นมาเรื่อยๆ นะครับ ขอบคุณครับ
