N

Nokfa Docs

ไม่มีชื่อบทความ

การสร้าง API ลงเวลา: route.js

1. ตำแหน่งไฟล์

สร้างไฟล์ใหม่ที่:

src/app/api/clock/route.js

ใช้รูปแบบ ESM (ไม่ใช้ CommonJS)

2. โค้ดตัวอย่างเต็ม

// src/app/api/clock/route.js

import { getCalendarClient } from '@/lib/googleClient';

// อนุญาตเฉพาะ POST method เท่านั้น
export async function POST(request) {
  try {
    // รับข้อมูลจาก body
    const { fullName, employeeCode, action } = await request.json();

    if (!fullName || !employeeCode || !['Check-in', 'Check-out'].includes(action)) {
      return Response.json({ message: 'Invalid payload' }, { status: 400 });
    }

    const calendar = getCalendarClient();

    // สร้าง timestamp server-side ตอนกดบันทึก
    const timestamp = Date.now();
    const startTime = new Date(timestamp).toISOString();
    const endTime = new Date(timestamp + 60000).toISOString(); // +1 นาที

    const event = {
      summary: `${fullName} (${employeeCode}) – ${action}`,
      description: 'Auto-generated time clock event',
      start: {
        dateTime: startTime,
        timeZone: 'Asia/Bangkok',
      },
      end: {
        dateTime: endTime,
        timeZone: 'Asia/Bangkok',
      },
      colorId: '2', // เลือกสีฟ้าอ่อน (optional)
    };

    await calendar.events.insert({
      calendarId: process.env.GOOGLE_CALENDAR_ID,
      requestBody: event,
    });

    return Response.json({ message: 'Clock-in event created' }, { status: 201 });

  } catch (error) {
    if (process.env.NODE_ENV !== 'production') {
      console.warn('Clock-in API Error:', error);
    }
    return Response.json({ message: 'Internal Server Error' }, { status: 500 });
  }
}

// รองรับ Preflight CORS สำหรับ development
export function OPTIONS() {
  return new Response(null, {
    status: 204,
    headers: {
      'Access-Control-Allow-Origin': process.env.NODE_ENV !== 'production' ? '*' : '',
      'Access-Control-Allow-Methods': 'POST, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type',
    },
  });
}

3. อธิบายโครงสร้าง

  • API นี้รับเฉพาะ POST เท่านั้น
  • รับ body { fullName, employeeCode, action }
  • Server ฝั่ง Next.js เป็นคนสร้าง timestamp เอง (ไม่ให้ client ส่ง timestamp มาเอง)
  • สร้าง Google Calendar Event ความยาว 1 นาที
  • กำหนด Timezone เป็น "Asia/Bangkok"
  • กำหนด Color (optional: เลือกสีฟ้าอ่อน colorId: '2')
  • Response Status:
    • 201 (Created) เมื่อสำเร็จ
    • 400 (Bad Request) ถ้า payload ผิด
    • 500 (Server Error) ถ้าเชื่อม Google Calendar ไม่สำเร็จ
  • มี OPTIONS สำหรับ Preflight CORS เฉพาะตอน dev

4. ตัวอย่างทดสอบ API ด้วย cURL

curl -X POST http://localhost:3000/api/clock \
  -H "Content-Type: application/json" \
  -d '{
    "fullName": "สมชาย ใจดี",
    "employeeCode": "E123",
    "action": "Check-in"
  }'

ผลลัพธ์ที่คาดหวัง

{
  "message": "Clock-in event created"
}

5. หมายเหตุเพิ่มเติม

  • การใส่ Color ใน Calendar Event ดูรายละเอียดเพิ่มเติมได้จาก Google Calendar API Events Colors
  • หากต้องการความแม่นยำของเวลาสูงกว่านี้ อาจใช้ process.hrtime หรือ external time server ในอนาคต

หมายเหตุ: หลังขั้นตอนนี้สามารถกดบันทึกเวลา และสร้าง Event จริงใน Google Calendar ได้แล้ว