[EP.2] Nest.js + MySql (Service , Database)
3 min read

[EP.2] Nest.js + MySql (Service , Database)

[EP.2] Nest.js + MySql (Service , Database)

ห่างหายกันมานาน เจ้าของบล๊อคงานยุ่งนิดหน่อยแต่ตอนนี้กลับมาทำแล้ว ใครยังไม่ได้อ่าน EP.1 ย้อนกลับไปดูได้นะครับ

[EP.1] Nest.js + MySql (Controller , Module)
Nest.js เป็น backend framework ที่ใช้ typescript เป็นภาษาในการเขียน มีconcept คล้ายกับ angular

เอาละเมื่อบทความที่แล้วเรา รุ้จัก 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;
}
users.entity.ts
@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
    }

   
}
users.service.ts

Service ตัวที่ทำการติดต่อกับ database จะไม่ใช้ Controllerในการติดต่อ

เราเตรียม service เสร็จแล้ว แต่ยังใช้งานไม่ได้เพราะเรายังไม่ได้นำมาใส่ใน Controller โดยการเพิ่ม Code ข้างล่างนี้ลงใน Controller

constructor(usersService: UsersService){}
users.controller.ts

จะเห็นว่ามันเป็นการ Injection ตัว Service เข้ามาใน UsersController จึงจำเป็นต้องกำหนดว่า Module นี้ ใช้ Service อะไรบ้าง โดยการเพิ่ม เข้าไปใน Module ตามนี้

@Module({
  imports: [TypeOrmModule.forFeature([UserEntity])],
  controllers: [UsersController],
  providers: [UserService],
})
export class UsersModule {}
users.module.ts

ต่อไป เรายังไม่ได้ 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 { }
app.module.ts

เชื่อมต่อ 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);
    }
   
}
users.service.ts
@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+

ปล. ถ้าเขียนไม่เข้าใจยังไง ก็ขออภัยด้วยนะครับ เจ้าของบล๊อคพิ่งจะหัดเขียนบทความ :) จะพยายามเขียนบทความขึ้นมาเรื่อยๆ นะครับ ขอบคุณครับ
personal-by-molysulfur/users-crud
Contribute to personal-by-molysulfur/users-crud development by creating an account on GitHub.

Documentation | NestJS - A progressive Node.js framework
Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Progamming), FP (Functional Programming), and FRP (Functional Reactive Programming).
typeorm/typeorm
ORM for TypeScript and JavaScript (ES7, ES6, ES5). Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Elect...