# การติดตั้งและสร้างโปรเจกต์ (Project Initialization) 1. ข้อกำหนดเบื้องต้น (Prerequisites) ก่อนเริ่ม, ตรวจสอบให้แน่ใจว่าคุณมีเครื่องมือเหล่านี้ติดตั้งบน Windows 11 ของคุณแล้ว: Node.js: เวอร์ชัน 18.x หรือสูงกว่า NPM หรือ Yarn: ตัวจัดการ Package (มักจะมาพร้อมกับ Node.js) NestJS CLI: เครื่องมือ Command-line สำหรับ NestJS หากยังไม่ได้ติดตั้ง NestJS CLI, ให้เปิด VS Code Terminal หรือ Command Prompt แล้วรันคำสั่ง: bash npm install -g @nestjs/cli ## 2.1 สร้างโปรเจกต์ NestJS ใหม่ ไปที่ Directory ที่คุณต้องการเก็บโปรเจกต์ (เช่น C:\Users\YourUser\Development\) ใช้ NestJS CLI เพื่อสร้างโปรเจกต์ใหม่ ผมจะตั้งชื่อว่า backend-np-dms นะครับ: Bash nest new backend ระบบจะถามว่าต้องการใช้ Package Manager ตัวไหน แนะนำให้เลือก npm, รอจนกว่ากระบวนการจะเสร็จสิ้น คุณจะได้โฟลเดอร์ backend ที่มีโครงสร้างพื้นฐานของ NestJS พร้อมใช้งาน ## 2.2 ติดตั้ง Dependencies ที่จำเป็น ตอนนี้เราจะติดตั้ง Modules ทั้งหมดที่คุณวางแผนไว้ในคราวเดียว เพื่อให้โปรเจกต์พร้อมสำหรับการพัฒนา เปิด Terminal ใน VS Code ภายในโฟลเดอร์ backend (cd backend) แล้วรันคำสั่งต่อไปนี้: * Database & ORM (TypeORM for MariaDB/MySQL) Bash npm install @nestjs/typeorm typeorm mysql2 * Configuration Management (สำหรับ .env) npm install @nestjs/config * API Documentation npm install @nestjs/swagger * Validation & Transformation npm install class-validator class-transformer * Security npm install helmet * Authentication (JWT) npm install @nestjs/passport passport passport-jwt @nestjs/jwt npm install --save-dev @types/passport-jwt คำอธิบาย: @nestjs/typeorm typeorm mysql2: สำหรับเชื่อมต่อและจัดการฐานข้อมูล MariaDB @nestjs/config: สำหรับจัดการ Environment Variables (เช่น ข้อมูลการเชื่อมต่อ DB) ผ่านไฟล์ .env @nestjs/swagger: สำหรับสร้างหน้าเอกสาร API (Swagger/OpenAPI) โดยอัตโนมัติ class-validator class-transformer: ใช้สำหรับตรวจสอบความถูกต้องของข้อมูลที่ส่งเข้ามาใน API (Request Body Validation) helmet: ช่วยเพิ่มความปลอดภัยพื้นฐานโดยการตั้งค่า HTTP Headers ที่เหมาะสม @nestjs/passport, @nestjs/jwt: เครื่องมือมาตรฐานสำหรับทำระบบ Authentication ## 2.3: ตั้งค่าพื้นฐานในโปรเจกต์ (Initial Configuration) ตอนนี้เราจะแก้ไขไฟล์หลักๆ เพื่อเปิดใช้งาน Modules ที่ติดตั้งไป 1. สร้างไฟล์ Environment (.env) ที่ราก (root) ของโปรเจกต์ backend-np-dms, สร้างไฟล์ใหม่ชื่อ .env และใส่ข้อมูลการเชื่อมต่อฐานข้อมูลของคุณ (ข้อมูลนี้จะไม่ถูกเก็บใน Git): .env Code snippet * Database Configuration DB_TYPE=mysql DB_HOST=localhost DB_PORT=3306 DB_USERNAME=your_db_user # <-- แก้ไขเป็น user ของคุณ DB_PASSWORD=your_db_password # <-- แก้ไขเป็น password ของคุณ DB_DATABASE=dms_db # <-- แก้ไขเป็นชื่อ database ของคุณ * Application API_PORT=3001 💡 Tip: หากคุณรัน MariaDB ผ่าน Docker, DB_HOST อาจจะเป็นชื่อ Service ของ Docker container (เช่น mariadb-container) หรือ IP ของ QNAP ของคุณ 2. แก้ไข app.module.ts เพื่อเชื่อมต่อ Database และ Config เปิดไฟล์ src/app.module.ts และแก้ไขให้เป็นตามนี้เพื่อ import ConfigModule และ TypeOrmModule: src/app.module.ts ```TypeScript import { Module } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { TypeOrmModule } from '@nestjs/typeorm'; import { AppController } from './app.controller'; import { AppService } from './app.service'; @Module({ imports: [ // 1. Config Module - สำหรับอ่าน .env (ต้องอยู่บนสุด) ConfigModule.forRoot({ isGlobal: true, // ทำให้ ConfigService พร้อมใช้งานทั่วทั้งแอป envFilePath: '.env', }), // 2. TypeORM Module - สำหรับเชื่อมต่อ Database TypeOrmModule.forRootAsync({ imports: [ConfigModule], inject: [ConfigService], useFactory: (configService: ConfigService) => ({ type: 'mysql', host: configService.get('DB_HOST'), port: configService.get('DB_PORT'), username: configService.get('DB_USERNAME'), password: configService.get('DB_PASSWORD'), database: configService.get('DB_DATABASE'), entities: [__dirname + '/../**/*.entity{.ts,.js}'], synchronize: true, // สำหรับ Development เท่านั้น! จะสร้างตารางให้อัตโนมัติ logging: true, }), }), ], controllers: [AppController], providers: [AppService], }) export class AppModule {} ``` ⚠️ คำเตือน: synchronize: true สะดวกมากในช่วงพัฒนาเพราะมันจะปรับโครงสร้างตารางตาม Entity ให้อัตโนมัติ ห้ามใช้ใน Production เด็ดขาด เพราะอาจทำให้ข้อมูลหายได้ ใน Production ควรใช้ระบบ Migration แทน 3. แก้ไข main.ts เพื่อเปิดใช้งาน Swagger, Validation และ Security เปิดไฟล์ src/main.ts และเพิ่มการตั้งค่าต่างๆ เข้าไป: src/main.ts TypeScript import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { ValidationPipe } from '@nestjs/common'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import helmet from 'helmet'; async function bootstrap() { const app = await NestFactory.create(AppModule); // เปิดใช้งาน CORS (Cross-Origin Resource Sharing) app.enableCors(); // เพิ่ม Helmet เพื่อความปลอดภัย app.use(helmet()); // ตั้งค่า Global Validation Pipe app.useGlobalPipes(new ValidationPipe({ whitelist: true, // ตัด property ที่ไม่มีใน DTO ออก transform: true, // แปลงข้อมูลให้เป็น type ที่ระบุใน DTO })); // ตั้งค่า Swagger API Documentation const config = new DocumentBuilder() .setTitle('LCBP3-DMS API') .setDescription('The Document Management System API for LCBP3 Project') .setVersion('1.0') .addBearerAuth() // สำหรับ JWT .build(); const document = SwaggerModule.createDocument(app, config); SwaggerModule.setup('api-docs', app, document); // เข้าถึงได้ที่ /api-docs // เริ่มรัน Server const port = process.env.API_PORT || 3001; await app.listen(port); console.log(`Application is running on: ${await app.getUrl()}`); } bootstrap(); curl -i -X POST \ -H "Content-Type: application/json" \ -d '{"username": "superadmin", "password": "Center#2025"}' \ https://backend.np-dms.work/api/auth/login