สร้าง RESTful API ด้วย NestJS และ MongoDB

สร้าง RESTful API ด้วย NestJS และ MongoDB: คู่มือฉบับสมบูรณ์

สร้าง RESTful API ด้วย NestJS และ MongoDB: คู่มือฉบับสมบูรณ์

ในโลกของการพัฒนาเว็บสมัยใหม่ การสร้าง RESTful APIs ที่มีประสิทธิภาพและปรับขนาดได้เป็นสิ่งสำคัญอย่างยิ่ง NestJS ซึ่งเป็นเฟรมเวิร์ก Node.js ที่ก้าวหน้า ช่วยให้การพัฒนาระบบหลังบ้านเป็นเรื่องง่ายดาย เมื่อใช้ร่วมกับ MongoDB ซึ่งเป็นฐานข้อมูล NoSQL ที่ยืดหยุ่น คุณสามารถสร้าง API ที่แข็งแกร่งและตอบสนองความต้องการของแอปพลิเคชันของคุณได้อย่างลงตัว

ทำไมต้อง NestJS และ MongoDB?

  • NestJS: เฟรมเวิร์กที่ใช้ Typescript ช่วยให้โค้ดของคุณมีความคงทนและบำรุงรักษาได้ง่าย มีโครงสร้างที่ชัดเจน ส่งเสริมการเขียนโค้ดที่เป็นระเบียบ และรองรับ Dependency Injection ทำให้ง่ายต่อการทดสอบและปรับขนาด
  • MongoDB: ฐานข้อมูล NoSQL ที่มีความยืดหยุ่นสูง สามารถจัดการข้อมูลที่ไม่มีโครงสร้างที่แน่นอนได้อย่างมีประสิทธิภาพ เหมาะสำหรับแอปพลิเคชันที่ต้องการความเร็วและความสามารถในการปรับขนาด

ขั้นตอนการสร้าง RESTful API ด้วย NestJS และ MongoDB

1. ติดตั้ง NestJS CLI

เริ่มต้นด้วยการติดตั้ง NestJS Command Line Interface (CLI) ทั่วโลก:

npm install -g @nestjs/cli

2. สร้างโปรเจกต์ NestJS ใหม่

ใช้ NestJS CLI เพื่อสร้างโปรเจกต์ใหม่:

nest new my-nestjs-mongodb-api

3. ติดตั้ง Mongoose

Mongoose เป็น Object Document Mapper (ODM) ที่ช่วยให้เราทำงานกับ MongoDB ได้ง่ายขึ้น ติดตั้ง Mongoose และ Types สำหรับ Node.js:

npm install --save mongoose @nestjs/mongoose @types/mongoose

4. กำหนดค่า Mongoose Module

แก้ไขไฟล์ app.module.ts เพื่อนำเข้าและกำหนดค่า MongooseModule:

import { Module } from '@nestjs/common';import { MongooseModule } from '@nestjs/mongoose';@Module({  imports: [    MongooseModule.forRoot('mongodb://localhost/mydatabase'), // Replace with your MongoDB connection string  ],  controllers: [],  providers: [],})export class AppModule {}    

5. สร้าง Schema และ Model

สร้างโฟลเดอร์ schemas และสร้างไฟล์ item.schema.ts:

import * as mongoose from 'mongoose';export const ItemSchema = new mongoose.Schema({  name: String,  description: String,  quantity: Number,});    

สร้างอินเทอร์เฟซสำหรับ Item ในไฟล์ item.interface.ts:

import { Document } from 'mongoose';export interface Item extends Document {  id: string;  name: string;  description: string;  quantity: number;}    

6. สร้าง Service

สร้างโฟลเดอร์ services และสร้างไฟล์ item.service.ts:

import { Injectable } from '@nestjs/common';import { InjectModel } from '@nestjs/mongoose';import { Model } from 'mongoose';import { Item } from '../interfaces/item.interface';import { CreateItemDto } from '../dto/create-item.dto';@Injectable()export class ItemsService {  constructor(@InjectModel('Item') private readonly itemModel: Model<Item>) {}  async findAll(): Promise<Item[]> {    return await this.itemModel.find().exec();  }  async findOne(id: string): Promise<Item> {    return await this.itemModel.findById(id).exec();  }  async create(createItemDto: CreateItemDto): Promise<Item> {    const createdItem = new this.itemModel(createItemDto);    return await createdItem.save();  }  async delete(id: string): Promise<Item> {    return await this.itemModel.findByIdAndRemove(id);  }  async update(id: string, item: CreateItemDto): Promise<Item> {    return await this.itemModel.findByIdAndUpdate(id, item, { new: true });  }}    

7. สร้าง Controller

สร้างโฟลเดอร์ controllers และสร้างไฟล์ item.controller.ts:

import { Controller, Get, Post, Put, Delete, Body, Param } from '@nestjs/common';import { CreateItemDto } from '../dto/create-item.dto';import { ItemsService } from '../services/item.service';import { Item } from '../interfaces/item.interface';@Controller('items')export class ItemsController {  constructor(private readonly itemsService: ItemsService) {}  @Get()  findAll(): Promise<Item[]> {    return this.itemsService.findAll();  }  @Get(':id')  findOne(@Param('id') id): Promise<Item> {    return this.itemsService.findOne(id);  }  @Post()  create(@Body() createItemDto: CreateItemDto): Promise<Item> {    return this.itemsService.create(createItemDto);  }  @Delete(':id')  delete(@Param('id') id): Promise<Item> {    return this.itemsService.delete(id);  }  @Put(':id')  update(@Param('id') id, @Body() updateItemDto: CreateItemDto): Promise<Item> {    return this.itemsService.update(id, updateItemDto);  }}    

8. สร้าง DTO (Data Transfer Object)

สร้างโฟลเดอร์ dto และสร้างไฟล์ create-item.dto.ts:

export class CreateItemDto {  readonly name: string;  readonly description: string;  readonly quantity: number;}    

9. นำเข้า Controller และ Service ใน AppModule

แก้ไขไฟล์ app.module.ts อีกครั้งเพื่อนำเข้า ItemsController และ ItemsService:

import { Module } from '@nestjs/common';import { MongooseModule } from '@nestjs/mongoose';import { ItemsController } from './controllers/item.controller';import { ItemsService } from './services/item.service';import { ItemSchema } from './schemas/item.schema';@Module({  imports: [    MongooseModule.forRoot('mongodb://localhost/mydatabase'),    MongooseModule.forFeature([{ name: 'Item', schema: ItemSchema }]),  ],  controllers: [ItemsController],  providers: [ItemsService],})export class AppModule {}    

10. ทดสอบ API

เรียกใช้แอปพลิเคชัน NestJS:

npm run start:dev

จากนั้นใช้เครื่องมืออย่าง Postman หรือ cURL เพื่อทดสอบ endpoints ต่างๆ เช่น:

  • GET /items - ดึงข้อมูลทั้งหมด
  • GET /items/:id - ดึงข้อมูลตาม ID
  • POST /items - สร้างรายการใหม่
  • PUT /items/:id - อัปเดตรายการตาม ID
  • DELETE /items/:id - ลบรายการตาม ID

สรุป

คู่มือนี้แสดงให้เห็นถึงวิธีการสร้าง RESTful API อย่างง่ายด้วย NestJS และ MongoDB คุณสามารถปรับปรุงและขยาย API นี้ได้ตามความต้องการของแอปพลิเคชันของคุณ ตัวอย่างเช่น คุณสามารถเพิ่มระบบ authentication, validation, และ error handling เพื่อให้ API ของคุณมีความปลอดภัยและเชื่อถือได้มากยิ่งขึ้น

หากคุณกำลังมองหาผู้เชี่ยวชาญด้านการพัฒนาซอฟต์แวร์ที่มีประสบการณ์ในการสร้าง RESTful APIs และโซลูชันดิจิทัลอื่นๆ ติดต่อ มีศิริ ดิจิทัล วันนี้เพื่อเริ่มต้นโครงการของคุณ!

มีศิริ ดิจิทัล คือผู้นำด้าน IT Consulting, Software Development, Digital Transformation, และ Business Solutions ในประเทศไทย ที่พร้อมช่วยให้ธุรกิจของคุณประสบความสำเร็จในยุคดิจิทัล

GitHub Copilot Guide for Thai Developers